javascript - 如何将点击事件添加到我存储在数组中的任何标记
问题描述
我正在使用传单 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);
}
推荐阅读
- android - 我需要使用广播接收器来获取前台应用程序吗?
- javascript - JavaScript RegExp 与标志 's' 和 'g' 匹配
- wso2 - 如何为 WSO2 EI 代理服务配置 HTTP 基本身份验证
- php - 如何在远程目录中使用 glob 函数
- flutter - 当列表的顺序发生变化时如何重新渲染ListView?
- python - html 报告期间的 python 覆盖错误(NoSource: No source for code:)
- php - Laravel 数据库通知在 Notification::send() 上做一些事情
- roku - Roku中的响应卷土重来
- javascript - 打开模态窗口时如何使背景模糊
- python - 如何使用python获取同一列中相同值之间的时间差