How do I make a single event handler for all markers in Google Maps V3?
I understand that if I have multiple markers on a map, and I need to handle clicks on them, I have to set up a handler for each marker like so:
// ...
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 hand开发者_StackOverflow社区ler here
});
But if I have a lot of markers, wouldn't it bee too heavy? Can I somehow set one handler and figure out which marker was clicked inside it?
To do it the way that I wanted to do is impossible, that's true. But I have found a way to do it another way which is a lot better than to have a handler per each marker. It should have been obvious to me, but it hasn't been:
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);
精彩评论