[GIS] How to add event listener to many markers on the map

leafletmarkers

How can I add an event listener to many markers on the map?
I know how to add an event listener to a single marker say:

var marker = L.marker(...);
marker.on('dragend',function(){...});

So, how can I add an event listener to many markers on the map?

In jQuery, you can select objects like this (example):

$(".marker").on("click",function(){...});

So this code applies it to all things with class marker.

Is there something similar to this with Leaflet?

Best Answer

You need to keep track of your markers in an array.

var markerArray = [];

Every time you add a marker you push it to the array.

var marker = new L.marker(...);
markerArray.push(marker);

Then if you wanted to apply some event listener to each of the markers you just iterate over that list.

for(var i=0;i<markerArray.length;i++){
    markerArray[i].on("click",function(){...});
}

Note the above code couldn't be copy/pasted since I didn't actually write the L.marker options or event callback function, but you should be able to pick it up from there.