Leaflet – How to Create Custom Layer Control for Leaflet Maps

leaflet

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

Best Answer

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