简体   繁体   English

单张打开单击按钮时会弹出特定标记

[英]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. 为此,我向标记添加了id属性,并将所有标记存储在数组中。 But for some reason, the id property of a marker inside of an array is undefined when I try to access it. 但是由于某些原因,当我尝试访问数组时,数组内部标记的id属性未定义。

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

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

And access markers as markers[i]["id"] 并将访问标记作为markers[i]["id"]

But can someone explain me why the first version doesn't work? 但是有人可以解释一下为什么第一个版本不起作用吗?

I think your mistake is the use of push (in markers.push(marker)) 我认为您的错误是使用push(在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 让标记知道其ID

marker.id = "id";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM