【问题标题】:How to map the pixel location of a marker on Google Map to Latitude and Longitude如何将谷歌地图上标记的像素位置映射到纬度和经度
【发布时间】:2017-04-04 13:31:23
【问题描述】:

我想添加将两个标记拖放到谷歌地图的功能,获取它们的经度和纬度并将其发送到后端服务器。这些标记的初始位置必须在一个固定点,以说明这个想象以下框作为包含谷歌地图的 div

 +++++++++++++++++++++
|                     |
|                  X  |
|                     |
|                     |
|                  Y  |
 +++++++++++++++++++++

XY 表示两个标记的初始位置。我面临的问题是:

  1. 我无法根据包含它们的div 设置标记。标记必须根据经度和纬度定位。
  2. 如果我想使用 CSS 将自己的标记添加到谷歌地图,那么问题是我无法获取定位标记的经度和纬度。

如何根据div本身,而不是地球的经纬度,将标记设置在固定位置?有没有办法将谷歌地图的像素位置映射到经度和纬度?

【问题讨论】:

  • 您想在点击时添加标记还是您知道标记的纬度?
  • @Akshaypadwal 我希望标记位于开头的特定位置(如上所示),以便用户可以在触摸设备上拖动标记,最后,我想保存 lat.并记录。标记所在的位置。
  • 一开始你一定有标记的纬度吧?
  • @Akshaypadwal 否,用户将设置标记的纬度。一开始标记将根据 div 放置(见上图),我不关心标记的纬度。

标签: javascript google-maps google-maps-api-3


【解决方案1】:

要进行此转换,您必须在自己的坐标参考系统中计算 div 和地图上显示区域的边界。然后您可以通过这种方式转换您的 x/y 坐标:

// Get the div's bounds
var divMap = document.getElementById('map');
var height = divMap.offsetHeight;
var width = divMap.offsetWidth;

// Get the map's bounds
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();

// Latitude-pixel ratio
var ratioLat = (ne.lat() - sw.lat()) / height;

// Longitude-pixel ratio
var ratioLng = (ne.lng() - sw.lng()) / width;

// Transform the x/y coordinates to lat/lng coordinates
// Assuming that you already have the relative x and y coordinates in your div
var transLat = y * ratioLat + sw.lat();
var transLng = x * ratioLng + sw.lng();
//OR you can do this
var transLat = ne.lat() - y * ratioLat;
var transLng = ne.lng() - x * ratioLng;

【讨论】:

  • 我已经编辑了答案,我认为这将完成答案
猜你喜欢
  • 2011-01-17
  • 1970-01-01
  • 2013-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多