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.
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)
You could also use a popup which can display HTML
marker.bindPopup(htmlString);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With