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作为补充参考.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...