Javascript 传单地图标记未按预期工作
我为数组“start”中的每个元素添加了一个标记“beginPoint”。初始化网页时,onclick函数会依次为每个标记运行,而我不会单击它们(这不是有意的) onclick函数向MyAPI发送一个请求,该请求将返回与单击的标记关联的“轨迹”的数据。最后,这些数据被注入到我的html页面中 因此,我的问题是,当我点击一个生成器时,onclick函数似乎不会触发,而是在加载所有生成器的te页面时运行。提前谢谢Javascript 传单地图标记未按预期工作,javascript,html,laravel,leaflet,leaflet.markercluster,Javascript,Html,Laravel,Leaflet,Leaflet.markercluster,我为数组“start”中的每个元素添加了一个标记“beginPoint”。初始化网页时,onclick函数会依次为每个标记运行,而我不会单击它们(这不是有意的) onclick函数向MyAPI发送一个请求,该请求将返回与单击的标记关联的“轨迹”的数据。最后,这些数据被注入到我的html页面中 因此,我的问题是,当我点击一个生成器时,onclick函数似乎不会触发,而是在加载所有生成器的te页面时运行。提前谢谢 //marker at the beginning of each track
//marker at the beginning of each track
var starts = Object.values(starts);
starts.forEach(function (element){
var latlng = new L.LatLng(element.Latitude, element.Longitude);
var beginPoint = L.marker(latlng, {icon:beginIcon}).addTo(mymap);
beginPoint.on('click', onClick(element.id));
});
}
//function called when clicking on marker @home
function onClick(e) {
var request = {
id: e
};
var url = "api/tracks/select"
fetch(url,
{
method: 'post',
headers: {'Content-type':'application/json'},
body: JSON.stringify(request)
}
)
.then(response => response.json())
.then(json => insertTrackDetails(json));
}
// set the data corresponding to the selected track
// to the details field in the home view
function insertTrackDetails(data){
var data = Object.values(data);
var image = data[0].image;
image = image.replace('public/images', '/storage/images');
document.getElementById('pills-detail').innerText = data[0].description;
document.getElementById('pills-image').src = image;
//TODO document.getElementById('pills-comments').innerText = data.description;
}
使用
()
在.on()
中添加函数时,该函数将立即执行,而不是在单击时执行。
因此,更改这个beginPoint.on('click',onClick(element.id))代码>到此起始点。在('click',onClick')代码>
那么您就有了如何知道id的问题。请将id添加到标记中,然后读取:
starts.forEach(function (element){
var latlng = new L.LatLng(element.Latitude, element.Longitude);
var beginPoint = L.marker(latlng, {icon:beginIcon}).addTo(mymap);
beginPoint.elmId = element.id; // store the id on the marker
beginPoint.on('click', onClick);
});
...
//function called when clicking on marker @home
function onClick(e) {
var id = e.target.elmId; // readout the id from the marker
var request = {
id: id
};
...