3

每次在地图上放置地图标记时,我都会尝试获取 POI 的经度和纬度。

这似乎有效,但它没有返回正确的 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>
4

1 回答 1

8

lon和将lat在“地图单位”中。仅当您的地图处于地理投影中时,这与经度和纬度相同。

要使其成为您期望的纬度和经度值,您需要transformLonLat对象上运行:

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()它。

于 2012-10-14T13:13:12.243 回答