我如何将一个点从[x,y]坐标投影到传单中的LatLng

How do I project a point from [x,y] coordinates to LatLng in Leaflet?

本文关键字:坐标 投影 LatLng 单中 一个      更新时间:2023-09-26

我使用的是传单1.0.0rc3,需要使用绝对像素值来修改我的地图上的东西。因此,我想知道用户在像素中单击的位置,然后将其转换回LatLng坐标。我尝试使用map.unproject(),这似乎是正确的方法(unproject()传单文档)。但该方法得到的LatLng值与e.latlng的输出值有很大的不同。(如输入LatLng (52, -1.7),输出LatLng (84.9, -177))。所以我一定是做错了什么。

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

这里有一个代码片段(fiddle: 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);
}

你只是使用了错误的方法。要在传单中将图层点转换为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。

您也可以查看传单提供的转换方法以获得额外参考。