Pixel to LatLng Google Maps API v3

Im sure you are like me and not interested in the reason why v3 has made a simple function such as fromContainerPixelToLatLng so complicated, however here is how I got it working.

In my working example I have created a div that hangs over the map div. When a user clicks and Drags the over-layed div the marker moves to the LatLng Coordinates of the map.

var myOptions = {
    zoom: 2,
    center: new google.maps.LatLng(25,25),
    mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
    document.getElementById("map"), 
    myOptions
);

var overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.setMap(map);

And now the magical function used in our click event for an object that is over-layed on-top of our maps. (Given that we are changing the position of a marker defined as `start_marker)

var coordinates = overlay.getProjection().fromContainerPixelToLatLng(
    new google.maps.Point(92, 61)
);

console.log(coordinates.lat + ", " + coordinates.lng);
start_marker.setPosition(coordinates);

Note the variables 92 and 61 are the left and top values of our map div.

By

posted on 10th May 2011
© 2011 Shahmir Javaid - http://shahmirj.com/blog/15

  • All messages are moderated so will only apear after being approved


  • #google-maps
  • #latlng
  • #api
  • #version3
  • #javascript
  • #jquery
  • #programming

Back to Top
All content is © copyrighted, unless stated otherwise.
Subscribe, @shahmirj, Shahmir Javaid+