1

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?

Shamdor
  • 3,019
  • 5
  • 22
  • 25
  • May be that would help: http://stackoverflow.com/questions/9329446/how-to-do-for-each-over-an-array-in-javascript – YaFred Jul 14 '14 at 05:04

1 Answers1

1

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";
YaFred
  • 9,698
  • 3
  • 28
  • 40
  • Yes, that is probably a better solution if I don't want marker to know it's id for some other reason. I'll think about it. But can you tell, why the first solution in my question didn't work? – Shamdor Jul 14 '14 at 15:16
  • use marker.id (not marker["id"]) as marker is not an array. I have updated the answer – YaFred Jul 14 '14 at 16:56
  • If this is the case, why my updated solution worked? I just don't understand the difference between them. – Shamdor Jul 14 '14 at 19:34