2016-09-08 283 views
4

我正在使用Leaflet 1.0.0rc3并需要使用绝对像素值来修改我地图上的某些内容。因此,我想知道用户点击像素的位置,然后将其转换回LatLng坐标。我尝试使用map.unproject(),这似乎是正确的方法(unproject() Leaflet documentation)。但是,该方法产生的LatLng值与e.latlng的输出值非常不同。 (例如,输入LatLng (52, -1.7)和输出LatLng (84.9, -177))。所以我一定在做错事。如何在Leaflet中投影从[x,y]坐标到LatLng的点?

问题:将图层(x,y)空间的点投影到LatLng空间的正确方法是什么?

下面是一个代码片段(小提琴:https://jsfiddle.net/ehLr8ehk/

// capture clicks with the map 
map.on('click', function(e) { 
    doStuff(e); 
}); 

function doStuff(e) { 
    console.log(e.latlng); 
    // coordinates in tile space 
    var x = e.layerPoint.x; 
    var y = e.layerPoint.y; 
    console.log([x, y]); 

    // calculate point in xy space 
    var pointXY = L.point(x, y); 
    console.log("Point in x,y space: " + pointXY); 

    // convert to lat/lng space 
    var pointlatlng = map.unproject(pointXY); 
    // why doesn't this match e.latlng? 
    console.log("Point in lat,lng space: " + pointlatlng); 
} 

回答

3

你只是用错了方法。要在Leaflet中将图层点转换为LatLng,您需要使用map.layerPointToLatLng(point)方法。

所以,你的代码应该是这样的:

// map can capture clicks... 
map.on('click', function(e) { 
    doStuff(e); 
}); 


function doStuff(e) { 
    console.log(e.latlng); 
    // coordinates in tile space 
    var x = e.layerPoint.x; 
    var y = e.layerPoint.y; 
    console.log([x, y]); 

    // calculate point in xy space 
    var pointXY = L.point(x, y); 
    console.log("Point in x,y space: " + pointXY); 

    // convert to lat/lng space 
    var pointlatlng = map.layerPointToLatLng(pointXY); 
    // why doesn't this match e.latlng? 
    console.log("Point in lat,lng space: " + pointlatlng); 
} 

而且一改jsFiddle

您也可以检查Leaflet提供的conversion methods以供其他参考。

+1

非常感谢 - 这正是我所需要的。对于我自己的笔记和读这个问题的其他人来说,'unproject'方法相对于CRS起源(我认为它是地图的绝对起源,而不是视图)转移,而'layerPointToLatLng'相对于[起源像素](http://leafletjs.com/reference-1.0.0.html#map-getpixelorigin)(请参阅[文档](http://leafletjs.com/reference-1.0.0.html#map-conversion-methods ))。 – user2441511

相关问题