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

SuperCell picture SuperCell · Mar 29, 2011 · Viewed 9.3k times · Source

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!

Answer

Bryan Johnson picture Bryan Johnson · Dec 3, 2013

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
)