redshift redshift - 3 months ago 9
Javascript Question

How to clear all layers AND clear input checkboxes?

I am using LeafletJS and building a custom layers input control with checkboxes to toggle on/off the various map layers.

My goal is to create a "clear all layers" button that, when clicked, will clear all the layers on the map AND remove all the checkmarks from the checkboxes.

The problem:

Toggling the layers off/on works fine when using the custom layers control, but I can't seem to figure out how to remove the checkmarks from the input boxes once the layers are removed from the map.

Here is my setup:

My HTML (note, doing this through L.Control.extend()):

<input type="checkbox" id="airfields" class="check">Airfields
<input type="checkbox" id="docks" class="check">Docks
... and so on

My JS:

var layerClicked = $(this).attr("id");
case "airfields":
if (map.haslayer(airfields)){
} else {
// ...and so on...

The above code obviously removes the layers from the map, but it doesn't remove the checkmarks from the input element.


If my understanding is correct, you are missing a "clear all" button that would untick all of your checkboxes, and remove the associated layers from map?

In that case, you would simply need to act on your button click, retrieve all your checkboxes, read if they are checked, and if so, trigger their "change"event and untick them.

$("#clearAll").click(function(event) {

  $(".check").each(function(i, el) {
    if (el.checked) {
      // Trigger the event.
      // Untick the checkbox.
      el.checked = false;


Note: you could have done it slightly simpler by reading the checked property on input change and remove/add the layer accordingly, instead of testing the layer presence on map. With your method, you may end-up with out-of-sync checkboxes (ticked whereas the layer is removed from map, and vice versa).

Something like:

if (this.checked) { map.addLayer(layer); }
else { map.removeLayer(layer); }