Google Maps API v3 - why there is no event context?

Using the Google Maps API v3 for the first time, and I have a map with a bunch of markers. I wanted to do this, when you click one, the specific InfoWindow (specific to the marker that you clicked) will be displayed. I was very surprised that the click event does not tell you the actual marker that was clicked!

I know there is a solution that uses a separate method to create a closure, but for me it seems like a hack. Is there a better way to do this? Or is there a way to ask the map β€œwhat markers exist in this position” and pass the position from the event argument?

I expected events to work as follows:

google.maps.event.addListener(marker, 'click', function(event, obj)
{
    //Now I can work with "obj" - the thing that was clicked.
});
+3
source share
3 answers

'this' .

google.maps.event.addListener(marker, 'click', function(e) {
  // this == marker;
  // e == MouseEvent
});
+10

, - click. . , :

function createMarker (point, map)
{
    var marker = new google.maps.Marker({
            position: point,
            map: map,
            title: "blah"});

    marker.stuffOnTheMarker = "Some interesting stuff";

    var content = buildSomeContentForThisMarker ();

    google.maps.event.addListener(marker, 'click', function() {
            infowindow.close ();
            infowindow.setContent(content); 
            infowindow.open(map,marker);

            // access the marker than caused this event
            alert (marker.stuffOnTheMarker);
        });
}
0

How to crack it when it is provided by the API? What you are describing is hacking. When you click on the marker, it will pass an event that contains lat and lng.

google.maps.event.addListener(marker, 'click', function(e) {
  console.log(e); // { x: 0, y: 0 }
});
0
source

All Articles