leaflet open specific marker popup on button click

蹲街弑〆低调 提交于 2019-12-25 04:22:24

问题


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?


回答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";


来源:https://stackoverflow.com/questions/24728245/leaflet-open-specific-marker-popup-on-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!