Simplify the toggling of layers on and off in a custom control with checkboxes?

前端 未结 1 766
甜味超标
甜味超标 2021-01-23 05:42

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

1条回答
  •  走了就别回头了
    2021-01-23 06:43

    $("#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/

    0 讨论(0)
提交回复
热议问题