0

How to make Leaflet markers go to unique link? Currently marker.on near the bottom gets the same link for each marker. I would like it to assign the corresponding link from var data for each. Cannot change the formatting too much as it links to other javascript pages as well

//sample data values for populate map
var data = [
    {"loc":[43.0680798,-89.4083302], "title":"Jordan's Big Ten Pub", "link":"Jordans_Big_Ten_Pub.html", "nid":"0"},
            {"loc":[43.0678893,-89.4064022], "title":"The Red Zone Madison", "link":"The_Red_Zone_Madison.html", "nid":"1"},
            {"loc":[43.0747636,-89.38156], "title":"Tipsy Cow", "link":"Tipsy_Cow.html", "nid":"52"}
];

var map = new L.Map('map', {zoom: 14, center: new L.latLng(43.072, -89.39) });  //set center from first location

map.addLayer(new L.TileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'));    //base layer
var markersLayer = new L.LayerGroup();  //layer contain searched elements
map.addLayer(markersLayer);
var controlSearch = new L.Control.Search({
    position:'topright',        
    layer: markersLayer,
    initial: false,
    zoom: 19,
    marker: false
});

map.addControl( controlSearch );

////////////populate map with markers from sample data
for(i in data) {
    var title = data[i].title,  //value searched
        loc = data[i].loc,
        j=data[i].nid,      //position found
        marker = new L.Marker(new L.latLng(loc), {title: title}, {win_url: data[i].link } );//se property searched
    marker.bindPopup('title: '+ title  );
    **marker.on('click', function(){window.location=(data[j].link)});**
    markersLayer.addLayer(marker);
    
}
1
  • Welcome to GIS SE. As a new user, please take the Tour. Please do not just post code. This is known as a "wall of code" post, and generally garners downvotes and close votes. Also, question quality is generally improved by writing out the full Question, then doubling back to write a title that describes the subject of the post. I took the liberty of transferring the on text to the body and making up a new title. Please take the opportunity to Edit the question with more details.
    – Vince
    Commented Aug 20, 2021 at 3:14

1 Answer 1

1

This could be done with your custom option win_url, but option must not be declared as a separate object, it has to be declared together with standard options. Code could then look something like this:

for (i in data) {
  var title = data[i].title,
    loc = data[i].loc,
    j=data[i].nid,
    marker = new L.Marker(new L.latLng(loc), {
      title: title,
      win_url: data[i].link
    });
  marker.bindPopup('title: '+ title  );
  marker.on('click', function(evt){
    window.location = evt.target.options.win_url;
  });
  markersLayer.addLayer(marker);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.