How do I make one event handler for all markers in Google Maps V3?

I understand that if I have multiple markers on the map and I need to handle clicks on them, I have to set up a handler for each marker, for example:

// ...
var marker = new google.maps.Marker({position: new google.maps.LatLng(55, 37)});
marker.setMap(map);
var listener = google.maps.event.addListener(marker, 'click', function(event){
    // my listener handler here
});

      

But if I have a lot of markers, isn't it too hard? Can I somehow set one handler and figure out which marker was pressed inside it?

+2


source to share


1 answer


It's impossible to do it the way I wanted to do it, it's true. But I found a way to do it in a different way, which is much better than having a handler for each marker. It should have been obvious to me, but it was not:



function markerHandler(event){
    window.console.log(this);
    // 'this' variable is the marker that has been clicked
}

var marker = new google.maps.Marker({position: new google.maps.LatLng(55, 37)});
marker.setMap(map);

var listener = google.maps.event.addListener(marker, 'click', markerHandler);

      

+5


source







All Articles