Shamdor
Shamdor

Reputation: 3099

leaflet open specific marker popup on button click

I'm trying to open a specific marker's popup on some event(say, button click). In order to do so I add an id property to a marker and store all markers in an array. But for some reason, the id property of a marker inside of an array is undefined when I try to access it.

var map = L.map('map').setView([51.505, -0.09], 13);
var markers = [];
var marker = L.marker([51.5, -0.09]);
marker["id"]="0";
marker.bindPopup('!');
marker.addTo(map);
markers.push(marker);

openPopupById("0");

function openPopupById(id) {
    for(var marker in markers) {
        alert("Marker's id " + marker["id"] + " target id " + id );
        if (marker["id"] === id) {
            //marker.openPopup();
            alert("opening " + id);
        }
    }
    alert(id);
}

UPDATE Ok, I found the solution: I should replace for with

for(var i = 0; i < markers.length; ++i)

And access markers as markers[i]["id"]

But can someone explain me why the first version doesn't work?

Upvotes: 1

Views: 6394

Answers (1)

YaFred
YaFred

Reputation: 10008

I think your mistake is the use of push (in markers.push(marker))

To store the markers, you should use

markers["id"] = marker;

You can open your popup like that

markers["id"].openPopup();

For the markers to know their id

marker.id = "id";

Upvotes: 1

Related Questions