7

I'd like to identify the layers that are currently active (which basemap is currently in view and which overlays are currently turned on).

Was hoping to find something akin to getActiveLayers in the Leaflet API (http://leafletjs.com/reference.html/) but I'm not seeing anything...

sfletche
  • 1,216
  • 1
  • 12
  • 24
  • yeah you gotta manage this yourself as far as i know. or use the plugin. I'm guessing the plugin subscribes to baselayerchange event and keeps track of the layer for you, which is how you do it without the plugin – nothingisnecessary Jul 29 '16 at 02:02

3 Answers3

9

Well, one option I've come across (to answer my own question) is a plugin created by vogdb.

This plugin contains methods getActiveBaseLayer() and getActiveOverlayLayers().

The following, from vogdb's github page, demonstrates how vogdb's activeLayers control can be used in place of the standard leaflet layers control making the 2 methods available.

var control = L.control.activeLayers(baseLayers, overlayLayers)
control.addTo(map)

console.log(control.getActiveBaseLayer().name)

var overlayLayers = control.getActiveOverlayLayers()
for (var overlayId in overlayLayers) {
    console.log(overlayLayers[overlayId].name)
}

The plugin can be found on github: https://github.com/vogdb/Leaflet.ActiveLayers

And for referencing purposes, I found the link to vogdb's plugin here: http://leaflet.uservoice.com/forums/150880-ideas-and-suggestions-for-leaflet/suggestions/3777550-get-active-baselayer

sfletche
  • 1,216
  • 1
  • 12
  • 24
2

The best answer is found here. You basically extend the class to add the method.

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;
  }
});
Rami Alloush
  • 121
  • 2
0

How to check if a leaflet layer is already added on the map?

You can use hasLayer method to check the current active layer when the map load first time to the browser.

As an example:

if(your_map_object.hasLayer(overlay_name_need_to_check)){
console.log("yes"); }

if your overlay currently active at the map object, this will print "yes" to console.