如何从谷歌地图(V3)LatLng获取屏幕XY? [英] How to get screen XY from google maps (V3) LatLng?

查看:219
本文介绍了如何从谷歌地图(V3)LatLng获取屏幕XY?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的地图中有折线。当用户点击折线时,我想知道像素(屏幕)xy坐标。 Click事件只返回LatLng对象,所以有人知道如何从latLng获取像素坐标吗?

I have polyline in my map. I want to know the pixel (screen) xy-coordinates, when user clicks the polyline. Click event only returns the LatLng object, so do anyone have a clue how to get the pixel coordinates from latLng?

如果有人能帮助我,我将非常感激!

I would appreciate very much if someone could help me!

推荐答案

如果您有LatLng对象,可以使用谷歌地图投影对象将其转换为平铺坐标,然后转换为像素坐标:

If you have the LatLng object, you can use the google map projection object to transform it into tile coordinates and then into pixel coordinates:

对于投影类的文档:
https://developers.google.com/maps/documentation/javascript/reference#Projection

Google的示例解释如何将LatLng转换为像素坐标:
https://developers.google.com/maps/documentation/javascript/examples/map-coordinates?csw=1

Google's example explaining how to transform a LatLng into a pixel coordinate: https://developers.google.com/maps/documentation/javascript/examples/map-coordinates?csw=1

有一个问题。以上将为您提供谷歌地图div内的像素坐标(您可能需要根据您的需要)。如果您想要相对于屏幕左上角的像素,还有一个步骤。您需要在视口的左上角执行相同的投影并减去两个投影。这将为您提供LatLng点的像素坐标。

There's one catch. The above will give you the pixel coordinates inside google's map div (which you may want depending on your needs). If you want the pixels relative to the top left corner of the screen, there's one more step. You need to do the same projection on the the viewport's top left corner and subtract the two. This will give you the pixel coordinates of the LatLng point.

我最终使用的代码如下所示(注意latLng是输入):

The code I finally used looked like this (note that "latLng" is an input):

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
)

这篇关于如何从谷歌地图(V3)LatLng获取屏幕XY?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆