Reputation: 35662
i have the (x,y)
(event.pageX-$("#map_canvas").offset().left,event.pageY-$("#map_canvas").offset().top)
but how to get the (lat,lng)
thanks
Upvotes: 1
Views: 2662
Reputation: 1398
Here's a code that doesn't rely on OverlayView(). This method makes use of the built in fromPointToLatLng() method in the maps API.
function pixelToLatlng(xcoor, ycoor) {
var ne = map.getBounds().getNorthEast();
var sw = map.getBounds().getSouthWest();
var projection = map.getProjection();
var topRight = projection.fromLatLngToPoint(ne);
var bottomLeft = projection.fromLatLngToPoint(sw);
var scale = 1 << map.getZoom();
var newLatlng = projection.fromPointToLatLng(new google.maps.Point(xcoor / scale + bottomLeft.x, ycoor / scale + topRight.y));
return newLatlng;
};
Source: http://magicalrosebud.com/how-to-use-googlemaps-api-frompointtolatlng/
Here's a fiddle: http://jsfiddle.net/mhaq865o/5/
Upvotes: 1
Reputation: 22241
Enter left and top pixel offset (x,y) and it returns a google.maps.LatLng
function PixelToLatLng(x,y){
var overlay = new google.maps.OverlayView()
overlay.setMap(map);
var LatLng = overlay.getProjection().fromContainerPixelToLatLng(new google.maps.Point(x,y));
overlay.setMap(null); delete overlay;
return LatLng;
}
Surprised this isn't in the google.maps.Map
object.
Upvotes: 0
Reputation: 2082
In your initialize function for a map define:
var overlay;
overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.setMap(map);
Next when you want to get the location run:
var point=new google.maps.Point(x,y);
var location=$overlay.getProjection().fromContainerPixelToLatLng(point);
Best K
Upvotes: 4