leaflet remove specific marker

前端 未结 1 1569
后悔当初
后悔当初 2021-01-06 06:06

I am very new to use Leaflet and its plugins. Currently I am working with a project to mark a specific location in the map with a marker.

But somehow I do not know h

相关标签:
1条回答
  • 2021-01-06 06:29

    Try with private properties, check on 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])
    
    0 讨论(0)
提交回复
热议问题