問題描述
非常簡單的問題:如何使 Leaflet 中的地圖標記可點擊并將用戶引導到其他頁面?每個標記都有自己的頁面.
Pretty simple question: How can I make the map markers in Leaflet clickable and route the user to an other page? Every marker has its own page.
我嘗試了以下方法但沒有成功;不知何故,所有標記都指向同一個頁面,這是最后分配的 URI.
I've tried the following without success; somehow all the markers point to the same page, which is the last assigned URI.
var markers = [
{ coords: [51.505, -0.09], uri: '/some-page' },
...
];
for(x in markers)
{
L.marker(markers[x].coords).on('click', function() {
window.location = markers[x].uri;
}).addTo(map);
}
這個問題真讓我抓狂.
推薦答案
好吧,我終于找到解決方案了;當標記添加到地圖時,它會被分配一個名為_leaflet_id"的 ID.這可以通過目標對象獲取,也可以在將其添加到地圖后設置為自定義值.
Okay, I finally came to a solution; when a marker is added to the map it gets assigned an ID called "_leaflet_id". This can be fetched through the target object, and also set to a custom value after it has been added to the map.
所以最終的解決方案很簡單:
So the final solution is simply:
var x = markers.length;
while(x--)
{
L.marker(markers[x].coords).on('click', function(e) {
window.location = markers[e.target._leaflet_id].uri;
}).addTo(map)._leaflet_id = x;
}
(我用反向的while循環替換了for-in循環)
(I replaced the for-in loop with a reversed while loop)
這篇關于傳單:添加標記的鏈接的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!