我正在尝试在某些事件(例如,按钮单击)上打开特定标记的弹出窗口.为此,我将 id 属性添加到标记并将所有标记存储在数组中.但是由于某种原因,当我尝试访问数组内的标记的 id 属性时,它是未定义的.
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);
}
更新好的,我找到了解决方案:我应该将 for
替换为
UPDATE
Ok, I found the solution: I should replace for
with
for(var i = 0; i < markers.length; ++i)
并以 markers[i]["id"]
但是谁能解释一下为什么第一个版本不起作用?
But can someone explain me why the first version doesn't work?
我认为你的错误是使用push(在markers.push(marker)中)
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();
让标记知道他们的 id
For the markers to know their id
marker.id = "id";
这篇关于传单在按钮单击时打开特定标记弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!