作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想添加将两个标记拖放到谷歌地图上的功能,获取它们的经度和纬度并将其发送到后端服务器。这些标记的初始位置必须位于固定点,以说明这一想象下面的框作为包含谷歌地图的div
+++++++++++++++++++++
| |
| X |
| |
| |
| Y |
+++++++++++++++++++++
X
和 Y
表示两个标记的初始位置。我面临的问题是:
div
设置标记。标记必须根据经度和纬度定位。如何根据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/
我是一名优秀的程序员,十分优秀!