gpt4 book ai didi

javascript - 如何将 Google map 上标记的像素位置映射为纬度和经度

转载 作者:行者123 更新时间:2023-12-03 05:36:25 25 4
gpt4 key购买 nike

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

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

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

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

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

最佳答案

要进行此转换,您必须在各自的坐标引用系中计算 div 的边界和 map 上显示的区域。然后你可以这样转换你的 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;

关于javascript - 如何将 Google map 上标记的像素位置映射为纬度和经度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40715348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com