Simplify the toggling of layers on and off in a cu

2020-04-30 02:56发布

问题:

This question is an off-shoot of this question I recently posted. I am wondering if there is a better way to check and toggle layers off/on when using a custom layers control. (Note: I also have a button that clears all the layers, if pressed.)

My custom layers control (L.Control.extend) looks like this:

var overlaysMenuCtrl = L.Control.extend({
    onAdd: function(map){
        var container = L.DomUtil.create('div', 'legend');
        container.innerHTML = 
'<input type="checkbox" id="airfields" class="check">Airfields
<input type="checkbox" id="docks" class="check">Docks
... and so on ...
<button id="clearAll">Clear All Layers</button>';
return container;
 }
});

And my JS looks like so (for the clearAll button):

$("#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;
}
})
});

For the toggling of layers off/on:

$(".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...
     }
  });

But, a poster on that linked question above suggested:

"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)."

Does anyone have any tips on how I could have done this in a more efficient way?

回答1:

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

  $(".check").each(function(i, el) {
    el.checked = false; // Set new status (unchecked) first.
    $(el).change(); // Trigger the event.
  })
});

$(".check").change(function() {
  var layerClicked = $(this).attr("id");
  switch (layerClicked) {
    case "airfields":
      toggleLayer(this.checked, airfields);
      break;
    case "docks":
      toggleLayer(this.checked, docks);
      break;
      // ...and so on...
  }
});

function toggleLayer(checked, layer) {
  if (checked) {
    map.addLayer(layer);
  } else {
    map.removeLayer(layer);
  }
}

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