Leaflet – Displaying Selected Layers Based on Zoom Level with Leaflet

geojsonjavascriptleaflet

It looks like I found the problem between the document.querySelector and map.on('zoomend') function.

I was going to set the zoom level for switching off some layers, what has been raised here:

Leaflet making features gone when zoom out

although there is a clash with the event .addEventListener function in my code.

In the result, when I switch off the layer, it's gone only for temporary zoom level.

When I change the zoom level it appears again, even when remains switched off on the sidebar (see image).

The code looks like:

    document.querySelector("input[name=cf]").addEventListener('change', function() {
            if(this.checked) map.addLayer(job)
              else map.removeLayer(job)
            })

   document.querySelector("input[name=vm]").addEventListener('change', function() {
            if(this.checked) map.addLayer(job2)
              else map.removeLayer(job2)
            })

    document.querySelector("input[name=bt]").addEventListener('change', function() {
            if(this.checked) map.addLayer(job3)
              else map.removeLayer(job3)
            })

and the part, which is responsible for specified zoom level for dissappearance

  map.on('zoomend', function() {
if (map.getZoom() <7){
        map.removeLayer(job);
}
if (map.getZoom() <7){
        map.removeLayer(job2);
}
if (map.getZoom() <7){
        map.removeLayer(job3);
}
else {
        map.addLayer(job);
        map.addLayer(job2);
        map.addLayer(job3);
    }
  });

Is it possible to combine these code together, making the layer invisible when scrolling between all zoom levels set in the map.on('zoomend' function ?

enter image description here

Best Answer

When trying to remove layer, you have to check if layer is currently added to the map with map.hasLayer method. When trying to add layer you have to check if layer is selected for display and if it's not currently added to the map.

Your zoomend function could then look something like this:

map.on('zoomend', function() {
  if (map.getZoom() < 7){
    if (map.hasLayer(job)) map.removeLayer(job);
    if (map.hasLayer(job2)) map.removeLayer(job2);
    if (map.hasLayer(job3)) map.removeLayer(job3);
  }
  else {
    if (document.querySelector("input[name=cf]").checked && !map.hasLayer(job)) map.addLayer(job);
    if (document.querySelector("input[name=vm]").checked && !map.hasLayer(job2)) map.addLayer(job2);
    if (document.querySelector("input[name=bt]").checked && !map.hasLayer(job3)) map.addLayer(job3);
  }
});