Leaflet/src/layer/LayerGroup.js
2012-11-07 18:46:59 +02:00

95 lines
1.7 KiB
JavaScript

/*
* L.LayerGroup is a class to combine several layers so you can manipulate the group (e.g. add/remove it) as one layer.
*/
L.LayerGroup = L.Class.extend({
initialize: function (layers) {
this._layers = {};
var i, len;
if (layers) {
for (i = 0, len = layers.length; i < len; i++) {
this.addLayer(layers[i]);
}
}
},
addLayer: function (layer) {
var id = L.Util.stamp(layer);
this._layers[id] = layer;
if (this._map) {
this._map.addLayer(layer);
}
this.fire('layeradd', { layer: layer });
return this;
},
removeLayer: function (layer) {
var id = L.Util.stamp(layer);
delete this._layers[id];
if (this._map) {
this._map.removeLayer(layer);
}
this.fire('layerremove', { layer: layer });
return this;
},
clearLayers: function () {
this.eachLayer(this.removeLayer, this);
return this;
},
invoke: function (methodName) {
var args = Array.prototype.slice.call(arguments, 1),
i, layer;
for (i in this._layers) {
if (this._layers.hasOwnProperty(i)) {
layer = this._layers[i];
if (layer[methodName]) {
layer[methodName].apply(layer, args);
}
}
}
return this;
},
onAdd: function (map) {
this._map = map;
this.eachLayer(map.addLayer, map);
},
onRemove: function (map) {
this.eachLayer(map.removeLayer, map);
this._map = null;
},
addTo: function (map) {
map.addLayer(this);
return this;
},
eachLayer: function (method, context) {
for (var i in this._layers) {
if (this._layers.hasOwnProperty(i)) {
method.call(context, this._layers[i]);
}
}
}
});
L.layerGroup = function (layers) {
return new L.LayerGroup(layers);
};