views:

40

answers:

2

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 handler 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?

+1  A: 

From what I understand about v3, it's impossible.

CrazyEnigma
+1  A: 

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);
Igor Zinov'yev
This is a good example of the implicit "this" context used when calling functions in javascript.
Richard Levasseur