1

I am trying to create a custom leaflet layer control for making layers visible or hidden. I created a html div which has a checkbox to hide or make visible a layer.

<input type="checkbox" id="layer1" name="Layer1"><label for="layer1"> LAYER 1</label><br>

I have created an example leaflet layer

var OpenRailwayMap = L.tileLayer('https://{s}.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: 'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors | Map style: &copy; <a href="https://www.OpenRailwayMap.org">OpenRailwayMap</a> (<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)'
    });

The problem I have now is how to use JavaScript to mark on the checkbox to show or hide the layer

1 Answer 1

3

This can be done by using oninput event handler for checkbox input element and .hasLayer, .addLayer and .removeLayer Leaflet map methods.

Relevant part of the code could then look something like this:

HTML

<input type="checkbox" id="layer1" name="Layer1" oninput="toggleLayer(this)"><label for="layer1"> LAYER 1 </label>

JS

function toggleLayer(element) {
  if (element.checked) {
    if (!map.hasLayer(OpenRailwayMap)) map.addLayer(OpenRailwayMap);
    }
  else {
    if (map.hasLayer(OpenRailwayMap)) map.removeLayer(OpenRailwayMap);
  }
}
document.getElementById('layer1').checked = map.hasLayer(OpenRailwayMap);
2
  • Worked as I wanted. Trying understand all the pieces (I am new to JS). I understand how the code works. The html runs the JS function. The JS function checks and adds or removes the layer. I don't understand what the last line does. I commented it out and the code still runs. Could you shed some light on it?
    – mapperx
    Commented Feb 10, 2023 at 15:22
  • 1
    Last line sets the value of the input checkbox to reflect the actual status of OpenRailwayMap layer: is it added to the map or not.
    – TomazicM
    Commented Feb 10, 2023 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.