如何在control.layers中获取所选图层?

时间:2017-06-02 06:35:43

标签: leaflet

是否可以使用小册子control.layers选择api中的所有选定图层?

我可以在jquery的帮助下这样做:

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

但也许有api

enter image description here

由于

2 个答案:

答案 0 :(得分:5)

没有API,但你可以自己轻松创建一个:

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

答案 1 :(得分:0)

基于iH8的答案

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

现在您可以使用

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

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

我觉得这很有用,因为

  • 包括所有图层
  • 键是图层的名称
  • 如果显示该图层,则其值为true,否则为false
相关问题