GetLonLat函数返回错误的LonLat

时间:2012-10-14 12:54:35

标签: javascript openlayers

每次在地图上放置地图标记时,我都会尝试获取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>

1 个答案:

答案 0 :(得分: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.

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

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