我无法创建指向单独动态页面的链接,当用户单击由传单创建的标记时,用户将被定向到该页面。下面的代码几乎完全有效;但是,当单击标记而不是转到相关页面时,所有标记都链接到循环生成的最后一个链接
//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;
}
答案 0 :(得分:2)
您必须创建一个关联数组,并将每个数据的键保留在标记对象中。
// 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];
这是example
答案 1 :(得分:1)
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;
}
}
另请参阅Leaflet marker event fires at wrong time,这几乎与您的问题重复。