Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get marker position in (x,y) in Google maps

Tags:

google-maps

I am using google maps. I want to display custom info-window on marker click. For that the upper-left tip of my custom info window should cover the marker.

The problem is I can not get the exact (x,y) ie map-div position of marker on map. For the first time I can get it using :

var mposition = map.fromLatLngToDivPixel(marker.getLatLng());
pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(mposition.x,mposition.y));

But when I drag the map, the marker position in x,y remains same and thus my info-window appears at wrong location. Please help me out how can I get the exact div-related position of marker on map even after drag/zoom.

Thanks.

like image 691
Prashant Avatar asked Dec 03 '22 13:12

Prashant


1 Answers

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

var proj = overlay.getProjection();
var pos = marker.getPosition();
var p = proj.fromLatLngToContainerPixel(pos);

You can now access your pixel coordinates through p.x and p.y.

Alternatively you could just try changing your fromLatLngToDivPixel to fromLatLngToContainerPixel. Before panning the map both functions will return the same values, but after moving or manipulating anything around in the map, the DivPixel function will return an updated value with regards to it's original position, ie: +x / +y pixels. The ContainerPixel function will return values with regards to the top left corner of your container div.

like image 66
Flarex Avatar answered Apr 02 '23 03:04

Flarex