微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何在Leaflet中将[x,y]坐标中的点投影到LatLng?

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

问题:将点(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);
}
最佳答案
你只是使用了错误方法.要在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 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作为补充参考.

原文地址:https://www.jb51.cc/js/429078.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐