Google Maps API V3 - add event listener to all markers?

Viewed 78651

There's got to be a way to add a listener to ALL MARKERS, currently I'm adding a listener to each one using a loop which feels really wrong...

This feels wrong:

google.maps.event.addListener(unique_marker_id, 'click', function(){
    //do something with this marker...                   
});   
11 Answers

This simplest way is this:

google.maps.event.addListener(marker, 'click', function() {
var marker = this;
alert("Tite for this marker is:" + this.title);
});

What i've Done is, when adding new marker on map and before pushing it into markers = [] array, i just add listener to it marker.addListener('click', () => { // Do Something here});

Complete Code:

// Adds a marker to the map and push to the array.
    function addMarker(location) {
        var marker = new google.maps.Marker({
            position: location,
            icon: {
                url: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"
            },
            animation: google.maps.Animation.DROP,
            map: map
        });
        marker.addListener("click",
            () => {
                console.log("Marker Click Event Fired!");
            });
        markers.push(marker);

    }

LINK i followed!

It was really hard for me to find a specific answer to my need. But this one is working now and everywhere for me! Regards! :)

Related