How to access Google Maps API v3 DIV marker and its pixel position?

Instead of the default info window of the Google Maps API, I'm going to use a different jQuery tooltip marker. So I need to get the DIV marker and its pixel position.

But it was not possible to get it, because for a specific marker there is no identifier or class. Only I can access the canvas div map from the marker object and the undocumented pixelBounds object.

  • How can I access the DIV marker?
  • Where can I get the pixel position of a DIV? Can I convert a lat-lng value to pixel values?

== attached:

I also tried using the code below, but it does not change when I look at the map.

var marker = new google.maps.Marker({...}); google.maps.event.addListener(marker, 'click', function() { var px = this.getMap().getProjection().fromLatLngToPoint(this.getPosition()); console.log("(" + px.x + "," + px.y + ")"); }); 
+20
google-maps google-maps-api-3
Apr 20 2018-10-10T00:
source share
10 answers

I really don't understand why you want to get a specific div for the marker? If you want to display a tooltip, then you only need the pixel position of the marker (and knowledge of the size of the marker and the location of the anchor), and not the div element. You can always launch a popup hint manually when an event occurs on the google.maps side.

To get the pixel position of the anchor of this marker, you can use this code:

 var scale = Math.pow(2, map.getZoom()); var nw = new google.maps.LatLng( map.getBounds().getNorthEast().lat(), map.getBounds().getSouthWest().lng() ); var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw); var worldCoordinate = map.getProjection().fromLatLngToPoint(marker.getPosition()); var pixelOffset = new google.maps.Point( Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale), Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale) ); 

In pixelDistance you get the offset of the specific marker anchor calculated from the upper left corner of the map (and you can get its position from the map.getDiv() div). Why does this work (or is there a better way?), You can read the Google map overlay documentation .

+45
Apr 22 '10 at 16:22
source share
 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); 

Now you can access your pixel coordinates via px and py

NEXT ADDED COMMENT:

The fall of the overlay projection is that until its map canvas finishes loading, it is not initialized. I have the following listener that will force any method that I need to call when the card finishes loading.

 google.maps.event.addListener(map, 'idle', functionName()); 

At the same time, I use the following check to avoid errors before I make it.

 if(overlay.getProjection()) { // code here } 
+8
Jul 12 2018-11-21T00:
source share

One thing to keep in mind when using the MBO code: When map tiles repeat, map.getBounds().getSouthWest() returns "-180" regardless of map position. The reservation I use in this case calculates the pixel distance to the center instead of the upper left corner, since map.getCenter() seems to return the current centered point anyway. For example. (using jQuery):

 // Calculate marker position in pixels form upper left corner var pixelCoordsCenter = map.getProjection().fromLatLngToPoint(map.getCenter()); pixelOffset = new google.maps.Point( Math.floor((pixelCoordsMarker.x - pixelCoordsCenter.x) * scale + $(container).width()/2), Math.floor((pixelCoordsMarker.y - pixelCoordsCenter.y) * scale + $(container).height()/2) ); 
+3
Sep 07 '11 at 6:27
source share

someone is still looking for an answer to this question, look here: http://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries among some other useful Google maps there is RichMarker stuff, which allows you to add DOM elements of your choice as draggable handles. just add the / id class to handle using jQuery.

+2
Dec 13
source share

Rene’s answer gives only “world coordinates” (ie, it does not depend on the zoom level and viewport). The MBO answer seems correct, however, so that the one you have to accept and vote (I cannot, because I just registered), as the solution can be easily skipped otherwise.

As for the “simpler” version, you can use the methods in MapCanvasProjection instead, but that means you will need to make your own overlay. See here for an example .: P

+1
Aug 22 '10 at 20:18
source share

MapCanvasProjection fromLatLngToContainerPixel() is probably the author. This will give you the pixel offset relative to the map container. I did some experimentation and found the “easiest” working solution. (I want Google to make this feature more accessible!)

First, you declare a subclass of OverlayView somewhere like this:

 function CanvasProjectionOverlay() {} CanvasProjectionOverlay.prototype = new google.maps.OverlayView(); CanvasProjectionOverlay.prototype.constructor = CanvasProjectionOverlay; CanvasProjectionOverlay.prototype.onAdd = function(){}; CanvasProjectionOverlay.prototype.draw = function(){}; CanvasProjectionOverlay.prototype.onRemove = function(){}; 

Then, somewhere else in your code where you create the map instance, you also create an instance of this OverlayView and set its map, for example:

 var map = new google.maps.Map(document.getElementById('google-map'), mapOptions); // Add canvas projection overlay so we can use the LatLng to pixel converter var canvasProjectionOverlay = new CanvasProjectionOverlay(); canvasProjectionOverlay.setMap(map); 

Then, when you need to use fromLatLngToContainerPixel , you simply do this:

 canvasProjectionOverlay.getProjection().fromLatLngToContainerPixel(myLatLng); 

Please note that since the MapCanvasProjection object will only be available after calling draw() , which once was before the idle map, I suggest creating a logical flag "mapInitialized", setting it to true on the first idle map callback. And then do what you need to do only after that.

+1
Aug 10 2018-11-21T00:
source share

Well, if you SHOULD access the DIV, here is some code. Remember that this will only work with a standard marker (20x34px) and it will find all the markers. You might want to improve this hack according to your needs ...

BEWARE! IT'S HUCH

 var a=document.getElementById('map_canvas'); var b=a.getElementsByTagName('img'); var i, j=b.length; for (i=0; i<j; i++) { if(b[i].src.match('marker_sprite.png')){ if(b[i].style.width=='20px' && b[i].style.height=='34px') { c=b[i].parentElement; console.log(c.style.top+":"+c.style.left); // this is a marker enclosing div } } } 
+1
May 22 '12 at 6:39
source share

Working jQuery snippet ready for copy / paste:

step 1 - initialize the map and parameters

 <html> <head> <script src="get-your-jQuery" type="text/javascript"></script> <script src="get-your-maps.API" type="text/javascript"></script> <script type="text/javascript"> <!-- $(document).ready(function(){ var bucharest = new google.maps.LatLng(44.43552, 26.10250); var options = { zoom: 14, center: bucharest, mapTypeId: google.maps.MapTypeId.ROADMAP } 

As you can see, below, the variable map is not preceded by a VAR, because it must be global, because we use another function to get fromLatLngToContainerPixel. See closures for more details.

 map = new google.maps.map($("#map_canvas")[0], options); var marker = new google.maps.Marker({ position: google.maps.LatLng(44.4407,26.0864), map: map }); new google.maps.event.addListener(marker, 'mouseover', function(){ placeMarker( marker.getPosition(),'#tooltip');//param1: latlng, param2: container to place result }); new google.maps.event.addListener(map, 'bounds_changed', function(){ $("#tooltip").css({display:'none'}); //this is just so you can see that all goes well ;) }); overlay = new google.maps.OverlayView(); overlay.draw = function() {}; overlay.setMap(map); }); //here ends jQuery.ready function placeMarker(location, ID){ var containerPixel = overlay.getProjection().fromLatLngToContainerPixel(location); var divPixel = overlay.getProjection().fromLatLngToDivPixel(location); $(ID).css({top:containerPixel.y, left:containerPixel.x, 'dislay':'block'}); } //--> </script> </head> <body> <div id="tooltip" style="width:100px; height:100px; position:absolute; z-index:1; background:#fff">Here I am!</div> <div id="map_canvas" style="width:300px; height:300px"></div> </body> </html> 
0
May 28 '12 at 14:35
source share

It was easier for me to assign a custom icon and use the img src attribute to access the element. You can still use the default Google map icon, just save it locally.

 $("#map img[src='my_marker.png']").getBoundingClientRect(); 
0
Jul 02 '14 at
source share

For many circumstances, the complex mathematics used to calculate and reposition the pin in the accepted answer may be appropriate.

For my specific use, I simply created a transparent PNG with a canvas significantly larger than what I need for the icon. Then I just experimented by moving a pin around a transparent background and applying a new image to the map.

setting pin offset in photoshop

Here is the specification for adding a custom pin image with examples: https://developers.google.com/maps/documentation/javascript/examples/icon-simple

This method definitely scales as an offset in pixels instead of the actual different long / lat, even if you zoom in.

0
May 6 '16 at 20:02
source share



All Articles