How to clear all layers AND clear input checkboxes?

柔情痞子 提交于 2019-12-25 09:48:19

问题


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:

$(".check").change(function(){
    var layerClicked = $(this).attr("id");
        switch(layerClicked){
            case "airfields":
                if (map.haslayer(airfields)){
                     map.removeLayer(airfields);
                } else {
                      map.addLayer(airfields);
                }
             break;
           // ...and so on...
         }
      });

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


回答1:


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) {
  event.preventDefault();

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

Demo: http://jsfiddle.net/3v7hd2vx/43/

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); }


来源:https://stackoverflow.com/questions/38485022/how-to-clear-all-layers-and-clear-input-checkboxes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!