如何将Google地图上标记的像素位置映射到纬度和经度

时间:2016-11-21 08:03:06

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

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

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

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

  1. 我无法根据包含它们的div设置标记。标记必须根据经度和纬度定位。
  2. 如果我想使用CSS将自己的标记添加到谷歌地图,那么问题是我无法获取定位标记的经度和纬度。
  3. 如何根据div本身将标记设置在固定位置,而不是根据地球的经度和纬度?有没有办法将谷歌地图的像素位置映射到经度和纬度?

1 个答案:

答案 0 :(得分: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;
相关问题