• Top
  • Comment
  • Reply

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

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

Hari Dahal

23rd Sep 2012

Thanks a lot sir. You help me to solve my problems.

filmai

30th Oct 2012

it doesn't work

Shahmir Javaid

30th Oct 2012

@Filmai, What exactly does not work?

Gelin Yan

12th Apr 2014

well..

getProjection() only works after overlay.onAdd is invoked.



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