2012-10-14 51 views
3

我試圖每次在地圖上放置地圖標記時都獲取POI的經度和緯度。GetLonLat函數返回不正確LonLat

這似乎工作,但它沒有返回正確的LonLat - 這是一個更大的數字,不是一個lonlat點。

GetLonLatFromPixel是正確的方法嗎?

爲凌亂的代碼提前道歉!

<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <style> 

     #heatmapArea { 
      position:relative; 
      float:left; 
      width:800px; 
      height:600px; 
      border:1px dashed black; 
     } 

    </style> 
</head> 
<body> 
<div id="main"> 
     <div id="heatmapArea"> 
     </div> 
<script src="http://openlayers.org/api/OpenLayers.js"></script> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> 
<script type="text/javascript"> 
var map, layer 
function init(){ 

//create new map position : 
       map = new OpenLayers.Map('heatmapArea'); 
       var layer   = new OpenLayers.Layer.OSM(); 
       var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984 
       var toProjection = new OpenLayers.Projection("EPSG:900913"); // 23834 to Spherical Mercator Projection 
       var position  = new OpenLayers.LonLat(0,51.4791).transform(fromProjection, toProjection); 
       var zoom   = 16; 

       map.addLayers([layer]); 
       map.setCenter(position,zoom); 
markers = new OpenLayers.Layer.Markers("Markers"); 
markers.id = "Markers"; 
map.addLayer(markers); 


//get lonlat: 
map.events.register("click", map, function(e) { 
    //var position = this.events.getMousePosition(e); 
    var position = map.getLonLatFromPixel(e.xy); 
    var size = new OpenLayers.Size(40,50); 
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h); 
var icon = new OpenLayers.Icon('eats.png', size, offset); 
var markerslayer = map.getLayer('Markers'); 

markerslayer.addMarker(new OpenLayers.Marker(position,icon)); 

$("<p>{lat:"+position["lat"]+",lon:"+position["lon"]+",count=1},</p>").insertAfter("p.longlat"); 

}); 



} 

window.onload = function(){ 
init(); 


}; 




</script> 

<div id="position"> 
<p class="longlat">LonLat</p> 

</div> 

</html> 

回答

7

The lon and lat will be in "map units". This is the same as longitude and latitude only if your map is in a geographic projection.

讓它成爲你所期望的緯度和經度值,則需要在LonLat對象運行transform

map.events.register("click", map, function(e) { 
    var toProjection = new OpenLayers.Projection("EPSG:4326"); 
    var position = map.getLonLatFromPixel(e.xy).transform(map.getProjectionObject(), toProjection); 
    ... 

(當然,你不需要經過創建toProjection對象的開銷,每次回調運行時,如果通過其他機制使回調可用)。

請注意,運行transform()將更改LonLat對象,因此如果您在地圖單位中需要它用於其他目的,請務必先將它設爲clone()

+0

啊哈,非常感謝。知道我錯過了一些明顯的東西。 – juicycoder

+0

這些「地圖單位」是一個特定的「投影」,OpenLayers.Projection(「EPSG:900913」); –