[GIS] Nothing happened when call function remove layer on leaflet

geojsonjavascriptleafletopenstreetmap

I'm tryng to call function for clear layer. But nothing happened,
using this

<li class="list-group-item">
      Remove All
      <div class="material-switch pull-right">
        <input id="removeAll" name="someSwitchOption001" type="checkbox" />
        <label for="removeAll" class="label-success"></label>
      </div>
    </li>

And this my script

    var map = new L.Map('map', {zoom: 8, center: new L.latLng([-2.9365327,  104.4950964]) });


  map.addLayer(new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')); //base layer
  <?php foreach ($map_link->result_array() as $i) :?>


    var <?= $i['maplink_var']; ?> = new L.GeoJSON(<?= $i['maplink_var']; ?>, {
      style: function(feature) {
        return {color: feature.properties.color };
      },
      onEachFeature: function(feature, marker) {
       const p = feature.properties;
       p.title = 'p.Name';

       marker.on('click', function (e) {

         var idlink="<?php echo $i['maplink_var']; ?>";
         var aab=feature.properties.ID;
         var numlat =  e.latlng.lat;
         var nlat = numlat.toFixed(3);
         var numlng = e.latlng.lng;
         var nlng = numlng.toFixed(3);

         marker.bindPopup('<td>'+feature.properties.Name+'</td><td>'+ nlat  +'</td><td>'+ nlng +'</td>');
       });

     }
   });
    function removeAllMarkers(){
      markers.clearLayers();
    }

    document.querySelector('removeAll').onclick=function(){removeAllMarkers()};
    map.addLayer(<?= $i['maplink_var']; ?>);

  <?php endforeach; ?>

is there an error in calling the Function ID? because there is no notification of an error, it's just that when I click nothing happens.

Best Answer

Instead of map.addLayer, you would be better off creating a LayerGroup or FeatureGroup and adding the layer to it. You then add the new Group to the map, now you can have your button remove all or a specific layer from the group.

// Creating Feature group
var featureGroup = L.featureGroup();

//Add layer to FeatureGroup
featureGroup.addLayer(yourLayer);

// Adding Feature group to map
featureGroup.addTo(map);

//remove a layer from FeatureGroup
featureGroup.removeLayers(yourLayer);

//remove all layers from FeatureGroup
featureGroup.clearLayers();