如何在leaflet.js中的标记上添加click事件

时间:2019-10-02 07:08:53

标签: javascript leaflet openstreetmap

我正在尝试为循环中的每个标记添加click事件。请参阅js代码。

我正在使用传单和OpenStreetMap开发具有多个可点击标记的地图。

var markers = [];

for (var i=0; i < selectedLocations.length; i++) 
{
  var image = selectedLocations[i].properties.image;
  var image_alt = selectedLocations[i].properties.image_alt;
  var name = selectedLocations[i].properties.name;
  var coords = selectedLocations[i].geometry.coordinates;
//set content in the infoWindow 
  const content = `<div id="infoWindow" style="width:150px; margin:2px;">
    <h2 style="font-size:14px; text-align:center;">${name}</h2>
    <img src="${image}" alt="${image_alt}" height="100px" width="150px">
    </div>`;

  markers[i] = L.marker([coords[1],coords[0]]).bindPopup(content).addTo(map);   
  markers[i].on('click',function(i){
    console.log(i);//in this code, the output i is always the length of the array
  });
}

我正在尝试基于值i调用函数。但是无论我单击哪个标记,i始终是数组的长度,而不是当前的I值。

2 个答案:

答案 0 :(得分:1)

@Denis的答案非常优雅(我不知道这种语法)

“经典”方式是向标记添加属性并从事件目标中获取值

markers[i] = L.marker([coords[1],coords[0]]).bindPopup(content).addTo(map); 
markers[i].id = i;  
markers[i].on('click',function(event){
  console.log(event.target.id);
});

答案 1 :(得分:0)

使用箭头功能处理点击。区别在于,它将在函数定义时记录i的值。

  markers[i].on('click',()=> {
    console.log(i);//in this code, the output i is always the length of the array
  });