2

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();
});
1

If the popup is bound to the marker, the click of the marker should fire it's associated popup (so you shouldn't need the marker.on('click', function(e){}) function).

Are you needing to fire the popup from events outside the map, based on the object's id?

1

If the marker successfully added to the map with

L.marker(map.unproject([element.LocationX,element.LocationY],map.getMaxZoom()-4)).addTo(map);

Then try:

$.each(data, function(index, element) {
    var marker = L.marker(map.unproject([element.LocationX,element.LocationY],map.getMaxZoom()-4)).addTo(map);
    marker.bindPopup(element.id);
    marker.on('click', function(e){
        this.openPopup();
    })

    // this part not clear: depends on how you need to get at markers later on
    markerArr.push(marker);
)}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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