2016-09-08 281 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

相關問題