Leaflet: add a link to markers

A rather simple question: how can I make map markers in the Leaflet clickable and redirect the user to another page? Each marker has its own page.

I tried the following without success; anyway, all tokens point to the same page, which is the last URI assigned.

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 problem is really driving me crazy.

+7
source share
3 answers

Well, I finally came to a decision; when a marker is added to the map, it is assigned an identifier called "_leaflet_id". This can be selected through the target, and also added to the custom value after it is added to the map.

So the final solution is simple:

 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 the inverse while loop)

+8
source

You can also use a popup that can display HTML

marker.bindPopup (HTMLString);

+3
source

I found a similar code that might help you. here's the jsfiddle link http://jsfiddle.net/farhatabbas/qeJ78/

  $(document).ready(function () { init_map(); add_marker(); }); var map; function init_map() { map = L.map('map').setView([37.8, -96], 4); L.tileLayer('http://{s}.tile.cloudmade.com/{key}/22677/256/{z}/{x}/{y}.png', { attribution: 'Map data &copy; 2011 OpenStreetMap contributors, Imagery &copy; 2012 CloudMade', key: 'BC9A493B41014CAABB98F0471D759707' }).addTo(map); } function add_marker() { var points = [ ["P1", 43.059908, -89.442229, "http://www.url_address_01.com/"], ["P2", 43.058618, -89.442032, "http://www.url_address_02.com/"], ["P3", 43.058618, -86.441726, "http://www.url_address_03.com/"] ]; var marker = []; var i; for (i = 0; i < points.length; i++) { marker[i] = new L.Marker([points[i][1], points[i][2]], { win_url: points[i][3] }); marker[i].addTo(map); marker[i].on('click', onClick); }; } function onClick(e) { console.log(this.options.win_url); window.open(this.options.win_url); } 
+1
source

All Articles