我的地图中有折线。当用户单击折线时,我想知道像素(屏幕)xy 坐标。点击事件只返回 LatLng 对象,那么有没有人知道如何从 latLng 获取像素坐标?
如果有人可以帮助我,我将不胜感激!
我的地图中有折线。当用户单击折线时,我想知道像素(屏幕)xy 坐标。点击事件只返回 LatLng 对象,那么有没有人知道如何从 latLng 获取像素坐标?
如果有人可以帮助我,我将不胜感激!
如果你有 LatLng 对象,你可以使用谷歌地图投影对象将其转换为瓦片坐标,然后转换为像素坐标:
对于投影类的文档: https ://developers.google.com/maps/documentation/javascript/reference#Projection
Google 的示例解释了如何将 LatLng 转换为像素坐标: https ://developers.google.com/maps/documentation/javascript/examples/map-coordinates?csw=1
有一个问题。以上将为您提供谷歌地图 div 内的像素坐标(您可能需要根据您的需要)。如果您想要相对于屏幕左上角的像素,还有一步。您需要在视口的左上角进行相同的投影并减去两者。这将为您提供 LatLng 点的像素坐标。
我最终使用的代码如下所示(注意“latLng”是一个输入):
var numTiles = 1 << map.getZoom();
var projection = map.getProjection();
var worldCoordinate = projection.fromLatLngToPoint(latLng);
var pixelCoordinate = new google.maps.Point(
worldCoordinate.x * numTiles,
worldCoordinate.y * numTiles);
var topLeft = new google.maps.LatLng(
map.getBounds().getNorthEast().lat(),
map.getBounds().getSouthWest().lng()
);
var topLeftWorldCoordinate = projection.fromLatLngToPoint(topLeft);
var topLeftPixelCoordinate = new google.maps.Point(
topLeftWorldCoordinate.x * numTiles,
topLeftWorldCoordinate.y * numTiles);
return new google.maps.Point(
pixelCoordinate.x - topLeftPixelCoordinate.x,
pixelCoordinate.y - topLeftPixelCoordinate.y
)