Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected layers in control.layers?

Tags:

leaflet

Is there a way to select all selected layers in the control.layers with leaflet api?

I can do it with the help of jquery like this :

$('.leaflet-control-layers-selector:checked')

But maybe there is an api?

enter image description here

Thanks

like image 255
SERG Avatar asked Jun 02 '17 06:06

SERG


2 Answers

Based on iH8's answer

L.Control.Layers.include({
  getOverlays: function() {
    // create hash to hold all layers
    var control, layers;
    layers = {};
    control = this;

    // loop thru all layers in control
    control._layers.forEach(function(obj) {
      var layerName;

      // check if layer is an overlay
      if (obj.overlay) {
        // get name of overlay
        layerName = obj.name;
        // store whether it's present on the map or not
        return layers[layerName] = control._map.hasLayer(obj.layer);
      }
    });

    return layers;
  }
});

Now you can use

var control = new L.Control.Layers(...)

control.getOverlays(); // { Truck 1: true, Truck 2: false, Truck 3: false }

I find this a little more useful because

  • all the layers are included
  • the key is the name of the layer
  • if the layer is showing, it has a value of of true, else false
like image 115
Cruz Nunez Avatar answered Oct 23 '22 01:10

Cruz Nunez


There is no API for that but you could easily create one yourself:

// Add method to layer control class
L.Control.Layers.include({
    getActiveOverlays: function () {

        // Create array for holding active layers
        var active = [];

        // Iterate all layers in control
        this._layers.forEach(function (obj) {

            // Check if it's an overlay and added to the map
            if (obj.overlay && this._map.hasLayer(obj.layer)) {

                // Push layer to active array
                active.push(obj.layer);
            }
        });

        // Return array
        return active;
    }
});

var control = new L.Control.Layers(...),
    active = control.getActiveOverlays();
like image 29
iH8 Avatar answered Oct 23 '22 01:10

iH8