Search code examples
javascriptleafletgeojsonlayer

How to remove L.GeoJSON layer when a new layer is added


I'm trying to remove my L.GeoJSON layer when ever i add a new layer via my dropdown menu. At the moment I can get the map to add a layer and zoom into it but when I select another country from my dropdown it zooms into the new layer and also adds it to the map, but doesn't remove the previous layer. I'm looking to have the previous layer removed every time I select another country

this is my current code.

 _callBack(coords) {
    const map = this.#map;
    var myStyle = {
      color: "  #80ff00",
      weight: 3,
      opacity: 0.5,
    };
    if (coords) {
      var LayerGroup = new L.LayerGroup();
      LayerGroup.addTo(map);
      var sMap = new L.GeoJSON(coords, { style: myStyle });
      LayerGroup.clearLayers();
      LayerGroup.addLayer(sMap);
      map.fitBounds(sMap.getBounds());
    }
  }

Solution

  • This happens because you are creating a new layer group every time you call a function. Declare your layer group and add it to map outside a function.

      var LayerGroup = new L.LayerGroup();
      LayerGroup.addTo(map);
     _callBack(coords) {
        const map = this.#map;
        var myStyle = {
          color: "  #80ff00",
          weight: 3,
          opacity: 0.5,
        };
        if (coords) {
          var sMap = new L.GeoJSON(coords, { style: myStyle });
          LayerGroup.clearLayers();
          LayerGroup.addLayer(sMap);
          map.fitBounds(sMap.getBounds());
        }
    }