小叶删除特定标记

时间:2017-08-29 06:19:18

标签: javascript html asp.net-mvc leaflet

我很擅长使用Leaflet及其插件。目前,我正在使用一个项目,使用标记在地图中标记特定位置。

但不知怎的,我不知道如果有多个标记,我怎样才能从地图中删除特定的标记。

标记绑定到弹出窗口,其中包含一些信息和框中的按钮。因此,我的目标是在单击按钮后删除特定标记。

var popupContent =
    '<p>Some Infomation</p></br>' +
    '<p>' + date + '</p></br>' +
    '<button onclick=clearMarker()>Clear Marker</button>';

myMarker = L.marker([lat, lng], { icon: redMarker, draggable: false });
var myPopup = myMarker.bindPopup(popupContent, { closeButton: false });
map.addLayer(myMarker);

如果我添加标记的方式有任何改进,请告诉我(非常确定有更好的方法来实现这一点)。

1 个答案:

答案 0 :(得分:1)

尝试使用私有媒体资源,请查看jsfiddle

var map = L.map('map').setView([51.505, -0.09], 13);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

var markers = []

function createMarker(coords) {
  var id
  if (markers.length < 1) id = 0
  else id = markers[markers.length - 1]._id + 1
  var popupContent =
    '<p>Some Infomation</p></br>' +
    '<p>test</p></br>' +
    '<button onclick="clearMarker(' + id + ')">Clear Marker</button>';
  myMarker = L.marker(coords, {
    draggable: false
  });
  myMarker._id = id
  var myPopup = myMarker.bindPopup(popupContent, {
    closeButton: false
  });
  map.addLayer(myMarker)
  markers.push(myMarker)
}

function clearMarker(id) {
  console.log(markers)
  var new_markers = []
  markers.forEach(function(marker) {
    if (marker._id == id) map.removeLayer(marker)
    else new_markers.push(marker)
  })
  markers = new_markers
}
createMarker([51.5, -0.09])
createMarker([51.5, -0.093])
createMarker([51.5, -0.096])