Convert from latitude and longitude to point/pixel in Google Maps V3

Hi all!

Migrating eattopia from google maps v2 to v3 in GWT we have had lots of problems. First is all those api changes. And… although v3 is much more complete it lacks some basic methods in V2. Our main headache has been converting from lat/lon to a point (pixel), just to know where to place the balloons in the map. At the, after investigating, we implemented the following method:

public static Point convertFromLatLngToPoint(LatLng latlng,GoogleMap map,Element elementContainingMap)
{
double worldMapWidth = 256*map.getZoom();

double mapWidth = elementContainingMap.getClientWidth();
double mapHeight = elementContainingMap.getClientHeight();

double mapLonRight = map.getBounds().getNorthEast().lng();
double mapLonLeft = map.getBounds().getSouthWest().lng();
double mapLonDelta= mapLonRight-mapLonLeft;

double mapLatBottom = map.getBounds().getSouthWest().lat();
double mapLatBottomDegree = mapLatBottom * Math.PI / 180;

double longitude = latlng.lng();
double latitude = latlng.lat();

double x = (longitude – mapLonLeft) * (mapWidth / mapLonDelta);

latitude = latitude * Math.PI / 180;
worldMapWidth = ((mapWidth / mapLonDelta) * 360) / (2 * Math.PI);
double mapOffsetY = (worldMapWidth / 2 * Math.log((1 + Math.sin(mapLatBottomDegree)) / (1 – Math.sin(mapLatBottomDegree))));
double y = mapHeight – ((worldMapWidth / 2 * Math.log((1 + Math.sin(latitude)) / (1 – Math.sin(latitude)))) – mapOffsetY);

Point result = Point.create(x, y);

return result;
}

About these ads

2 comments

  1. Raymond · · Reply

    Thank you so so much! I managed to spend an entire day looking for how to do this before I found your post. Ugh! Thank you so much for your help!

    1. And your comment made my day :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 157 other followers

%d bloggers like this: