Leaflet: Add a link to the markers

前端 未结 3 501
青春惊慌失措
青春惊慌失措 2021-01-12 02:47

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.

I\'ve tried the follo

3条回答
  •  Happy的楠姐
    2021-01-12 03:44

    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;
    }
    

    (I replaced the for-in loop with a reversed while loop)

提交回复
热议问题