Im having trouble creating links to a separate dynamic page, where the user is directed to the page when they click a marker created by leaflet. The code below almost entirely works; however, when the marker is clicked instead of going to the relevant page, all the markers link to the last link generated by the loop
//Add a marker to the map on the results page for each result
function Addmarker(markerArray){
var dynamicname = 'marker';
var dynamicnumb = 'numb';
//create an empty list to hold each marker
var markerList = [];
//For each result creater a marker and push it to markerList
for (i = 0; i < markerArray.length; i++) {
//Turn the park id into an integer
var toInt = parseInt(markerArray[i][2]);
//Generate the marker in the form L.marker(Latitude, Longitude, Name of Park to be shown on mouse over, link to the individual item page on click).add the marker to mymap
this[dynamicname+i] = L.marker([markerArray[i][0], markerArray[i][1]], {title: markerArray[i][3]}).on('click', function(e) {markerURL(toInt);}).addTo(mymap);
//Place the marker in a list
markerList.push(this[dynamicname+i]);
}
//Create a feature group of the markers in markerList
var group = new L.featureGroup(markerList);
//Auto scale the map to fit all the markers perfectly
mymap.fitBounds(group.getBounds().pad(0.2));
}
//create a dynimic link to the individual items page specified in the parameter itemsID
function markerURL(itemsID){
window.location.href = 'Items.php?parkid=' + itemsID;
}
You must create an associative array and keep the key of each data in the marker object.
// generate a unique id
var toInt = parseInt(markerArray[i][2]);
// create marker object, add it to the map
var marker = L.marker([markerArray[i][0], markerArray[i][1]], {
title: markerArray[i][3]}).on('click', function(e) {
markerURL(e.target.ID); // url = markerList[e.target.ID][3];
}).addTo(map);
// keep the unique id in the marker object
marker.ID = toInt;
// create an item in the associative array
markerList[toInt] = markerArray[i];
Here is an example
function Addmarker(markerArray){
for (i = 0; i < markerArray.length; i++) {
var toInt = parseInt(markerArray[i][2]);
this[dynamicname+i] = L.marker(
[markerArray[i][0], markerArray[i][1]],
{title: markerArray[i][3]}
).on('click', onMarkerClick(toInt)).addTo(mymap);
}
function onMarkerClick(itemsID){
return function(ev) {
window.location.href = 'Items.php?parkid=' + itemsID;
}
}
See also Leaflet marker event fires at wrong time , which is pretty much a duplicate of your question.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.