zjm1126
zjm1126

Reputation: 35662

how to get the location(lat/lng) on google maps v3 from the location(x,y)

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

Answers (3)

Byron Singh
Byron Singh

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

iambriansreed
iambriansreed

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

kwicher
kwicher

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

Related Questions