1
votes

I have a set of 23 mapbox layers I can toggle on and off independently. I would like to include a master OFF ALL toggle. How can I accomplish this? Here are the code:

<script type="text/javascript">
var map = L.map('map',{center: [56.5, -1], minZoom: 7, zoomControl: false, legendControl: true}).setView([56.5, -1], 7);
map.addControl(new L.Control.ZoomMin())
var baseLayer = new L.mapbox.tileLayer('inosys.k52e98ob').addTo(map);
var ui = document.getElementById('map-ui');

var overlays = [
['inosys.k8mg7jp2','Toggle All On', 1], 
['#','Toggle All Off', 1], 
['inosys.jgsk2of8','Significant Discoveries', 999999],
['inosys.gaa3x433','Wells', 999999],
['inosys.gaa3xpkf','Hydrocarbon Fields', 3],
['inosys.u0uttr1z','Field Determinations', 3],
....
1
possible duplicate of Master layer toggles in Mapbox - tmcw

1 Answers

2
votes

On selection of the Toggle button, you could run a function that iterated across all the layers and removed them like so:

function toggleAllOff(){
  map.eachLayer(function (layer) {
    map.removeLayer(layer);
  });
}

You could also add all the layers to a single LayerGroup and then call clearLayers on that group as documented on another question here.

Edit: The below shows the code needed to work in your particular case. It's slightly hacky in that the method removes the base layer and I add it back in. You could do a quick check for that if you didn't want to remove the base layer.

link.onclick = function (e) {
    e.preventDefault();
    e.stopPropagation();

//Add the following
    if ($(this).text() == 'Toggle All Off') {
        map.eachLayer(function (layer) {
            map.removeLayer(layer);
        });
        map.addLayer(baseLayer);
    } else if (map.hasLayer(layer)) {

//The rest is your old code
        map.removeLayer(layer);
        map.removeLayer(gridlayer);
        map.removeControl(gridControl);
        map.removeControl(legendControl);
        this.className = '';