如何解决如何将点击事件添加到我存储在数组中的任何标记中
我正在使用传单js,我有一个数组,其中存储了我的标记,这些标记在获得用户位置后会自动添加到地图中。 问题是我想添加一个onclick侦听器,以便单击的任何标记都可以运行一个功能。 请帮助我,因为我现在被困住了。
//objects for markers
var allMarkers=[];
var AllMarkers = L.layerGroup(allMarkers);
var Allpoints=[{
"latitudes":9.4258946,"longitudes":-0.8842213,"names":"first","eastings":556568,"northings":446445,"description": "aijaskj jnrkajra skjanjanek ","elevations": 5668
},{
"latitudes":9.4254946,"longitudes":-0.8812213,"names":"second"},{
"latitudes":9.4054946,"longitudes":-0.8802213,"names":"third"},{
"latitudes":9.4754946,"longitudes":-0.8712213,"names":"fourth"},];
//automatically plot all previous markers
var point = L.point(9.2754946,-0.8912213);
q = 0;
while(q< Allpoints.length){
//create Marker here
_newMarker = L.marker(
[Allpoints[q].latitudes,Allpoints[q].longitudes],{title: Allpoints[q].names,riseOnHover: true,} ).addTo(mymap);
allMarkers.push(_newMarker);
q++
}
//function to send back the details of the clicked marker to a paragraph in my index.htm
//PROBLEM
L.marker('click',markers,showMarkerDetails) //however the code immediately above does not work
function showMarkerDetails(){
$("#returnControlName").html(controlName);
$("#returnControlLocation").html(`${controlLat.toFixed(4)},${controlLong.toFixed(4)} `);
$("#returnControlEastings").html(controlEastings);
$("#returnControlName").html(controlNorthings);
$("#returnControlName").html(controlElevation);
$("#returnControlName").html(controlDescription);
}
解决方法
使用L.marker()
将新的标记/点添加到地图中,则无法向其添加此类事件。 (L.marker('click',markers,showMarkerDetails)
)
将您的代码更改为:
//automatically plot all previous markers
var point = L.point(9.2754946,-0.8912213);
q = 0;
while(q< Allpoints.length){
//create Marker here
_newMarker = L.marker([Allpoints[q].latitudes,Allpoints[q].longitudes],{title: Allpoints[q].names,riseOnHover: true,}).addTo(mymap);
_newMarker.informations = Allpoints[q]; // save the data to the marker to read it later out
_newMarker.on('click',showMarkerDetails); // add click event to the markers
allMarkers.push(_newMarker);
q++
}
function showMarkerDetails(e){
var layer = e.target // get the clicked marker
var infos = layer.informations;
console.log(infos.description);
$("#returnControlName").html(controlName);
$("#returnControlLocation").html(`${controlLat.toFixed(4)},${controlLong.toFixed(4)} `);
$("#returnControlEastings").html(controlEastings);
$("#returnControlName").html(controlNorthings);
$("#returnControlName").html(controlElevation);
$("#returnControlName").html(controlDescription);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。