Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet: Add a link to the markers

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

This issue is really driving me nuts.

like image 658
Ivar Avatar asked Dec 19 '12 13:12

Ivar


2 Answers

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)

like image 168
Ivar Avatar answered Sep 21 '22 12:09

Ivar


You could also use a popup which can display HTML

marker.bindPopup(htmlString);

like image 33
dnns Avatar answered Sep 22 '22 12:09

dnns