我正在尝试在某些事件(例如,按钮单击)上打开特定标记的弹出窗口.为此,我将 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模板网!
检查一个多边形点是否在传单中的另一个内部Check if a polygon point is inside another in leaflet(检查一个多边形点是否在传单中的另一个内部)
更改传单标记群集图标颜色,继承其余默认 CSSChanging leaflet markercluster icon color, inheriting the rest of the default CSS properties(更改传单标记群集图标颜色,继承其余默认
触发点击传单标记Trigger click on leaflet marker(触发点击传单标记)
如何更改 LeafletJS 中的默认加载磁贴颜色?How can I change the default loading tile color in LeafletJS?(如何更改 LeafletJS 中的默认加载磁贴颜色?)
将外部geojson添加到传单层Add external geojson to leaflet layer(将外部geojson添加到传单层)
将 Leaflet 图层控件添加到侧边栏Adding Leaflet layer control to sidebar(将 Leaflet 图层控件添加到侧边栏)