0

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?

1 Answer 1

2

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.

3
  • Thank, but now I have this issue: When I write something like: markerArray[i].getLatLng(), it gives me this Uncaught TypeError: Cannot call method 'getLatLng' of undefined
    – Enrique
    Mar 30, 2014 at 20:12
  • Whats the issue? Are you getting an error?
    – Taylor H.
    Mar 30, 2014 at 20:15
  • @Enrique Do you recall how you solved your issue?
    – jthomas
    Dec 11, 2014 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.