How to clear leaflet map of all markers and layers before adding new ones?

前端 未结 6 1535
遇见更好的自我
遇见更好的自我 2021-02-05 00:02

I have the fallowing code:

map: function (events) {
    var arrayOfLatLngs = [];
    var _this = this;

    // setup a marker group
    var markers = L.markerClu         


        
相关标签:
6条回答
  • 2021-02-05 00:33

    I used a combination of the two best answers here from beije and Prayitno Ashuri.

    Saving the markers to "this" so we can reference it later.

    this.marker = L.marker([event.location.lat, event.location.lng]);
    

    and then just removing the markers.

    this.markers.remove()
    
    0 讨论(0)
  • 2021-02-05 00:45

    You can clear all markers withought saving it

    map.eachLayer((layer) => {
      layer.remove();
    });
    

    from https://leafletjs.com/reference-1.0.3.html#map-event

    0 讨论(0)
  • 2021-02-05 00:46
    $(".leaflet-marker-icon").remove();
    $(".leaflet-popup").remove();
    
    0 讨论(0)
  • 2021-02-05 00:50

    If you want to remove all the current layers (markers) in your group you can use the clearLayers method of L.markerClusterGroup(). Your reference is called markers so you would need to call:

    markers.clearLayers();
    
    0 讨论(0)
  • 2021-02-05 00:53

    You're losing the marker reference because it's set with var. Try saving the references to 'this' instead.

    mapMarkers: [],
    map: function (events) {
        [...]
        events.forEach(function (event) {
            [...]
            // create the marker
            var marker = L.marker([event.location.lat, event.location.lng]);
            [...]
            // Add marker to this.mapMarker for future reference
            this.mapMarkers.push(marker);
        });
        [...]
    }
    

    Then later when you need to remove the markers run:

    for(var i = 0; i < this.mapMarkers.length; i++){
        this.map.removeLayer(this.mapMarkers[i]);
    }
    

    Alternatively, instead of saving each reference to each marker, you can just save the cluster to 'this'.

    0 讨论(0)
  • 2021-02-05 00:54
    map._panes.markerPane.remove();
    
    0 讨论(0)
提交回复
热议问题