BaconJuice
BaconJuice

Reputation: 3769

How to open a popup on Marker click when Markers are in array using leaflet maps

Hey guys I have a set of Markers that are getting created dynamically on a .each loops like so.

$.each(data, function(index, element) {
    markerArr[element.id] = L.marker(map.unproject([element.LocationX,element.LocationY],map.getMaxZoom()-4)).addTo(map);
});

My question is how to open the popup for each popup on click and show the unique ID inside the popup?

I am able to do this if I were to declare each Marker with a unique name like so.

var marker1 = L.marker([158,395]).addTo(mapl);
var marker2 = L.marker([158,410]).addTo(mapl);
marker1.bindPopup("Kanye West");
marker1.on('click', function (e) {
    this.openPopup();
});
marker2.bindPopup("50 Cent");
marker2.on('click', function (e) {
    this.openPopup();
});

But I need to be able to open all Markers that are in the array instead.

Tried something like this with no luck

markerArr[this].on('click', function (e) {
    this.openPopup();
});

Any help would be greatly appreciated.

Thank you.

Upvotes: 1

Views: 9596

Answers (1)

Alex Morega
Alex Morega

Reputation: 4228

You don't need to write the click event handler yourself. If you call marker.bindPopup("hello"), the popup will open automatically on click.

Upvotes: 9

Related Questions