Filter Leaflet Geojson object based on Checkbox st

2019-06-10 15:16发布

问题:

I've been trying to adapt this example to filter a leaflet layer based on the checkbox ID. It kind of works where the enabled object gets filled and the corresponding feature is filtered and added to the map.

However, when I uncheck the box object becomes empty but the feature remains on the map as there is nothing to tell if to be removed.

What do I need to do here to remove the feature?

   function update() {
        var enabled = {};
        // Run through each checkbox and record whether it is checked. If it is,
        // add it to the object of types to display, otherwise do not.
        for (var i = 0; i < checkboxes.length; i++) {
          if (checkboxes[i].checked) enabled[checkboxes[i].id] = true;
         }
        L.geoJson(parishesData, {
        filter: function(feature, layer) {
            return (feature.properties.name in enabled);
            }
        }).addTo(map);
        console.log(enabled)
        };

回答1:

Whenever your script executes your update() function, it creates a new L.geoJson group and adds it to the map.

You should keep a reference to that group and remove it from map before you add the new one to the map.

Probably something like:

var group;

function update() {
  var enabled = {};
  // Run through each checkbox and record whether it is checked. If it is,
  // add it to the object of types to display, otherwise do not.
  for (var i = 0; i < checkboxes.length; i++) {
    if (checkboxes[i].checked) enabled[checkboxes[i].id] = true;
  }
  if (group) {
    map.removeLayer(group);
  }
  group = L.geoJson(parishesData, {
    filter: function(feature, layer) {
      return (feature.properties.name in enabled);
    }
  }).addTo(map);
  console.log(enabled)
};