How to get screen XY from Google maps (V3) LatLng?

大憨熊 提交于 2019-12-07 11:41:37

问题


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 does anyone have a clue how to get the pixel coordinates from latLng?

I would appreciate very much if someone could help me!


回答1:


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:

For the docs on the projection class: https://developers.google.com/maps/documentation/javascript/reference#Projection

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

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.

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
)


来源:https://stackoverflow.com/questions/5471848/how-to-get-screen-xy-from-google-maps-v3-latlng

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!