UNPKG

2.79 kBJavaScriptView Raw
1import {LayerGroup} from './LayerGroup';
2import {LatLngBounds} from '../geo/LatLngBounds';
3
4/*
5 * @class FeatureGroup
6 * @aka L.FeatureGroup
7 * @inherits LayerGroup
8 *
9 * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
10 * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
11 * * Events are propagated to the `FeatureGroup`, so if the group has an event
12 * handler, it will handle events from any of the layers. This includes mouse events
13 * and custom events.
14 * * Has `layeradd` and `layerremove` events
15 *
16 * @example
17 *
18 * ```js
19 * L.featureGroup([marker1, marker2, polyline])
20 * .bindPopup('Hello world!')
21 * .on('click', function() { alert('Clicked on a member of the group!'); })
22 * .addTo(map);
23 * ```
24 */
25
26export var FeatureGroup = LayerGroup.extend({
27
28 addLayer: function (layer) {
29 if (this.hasLayer(layer)) {
30 return this;
31 }
32
33 layer.addEventParent(this);
34
35 LayerGroup.prototype.addLayer.call(this, layer);
36
37 // @event layeradd: LayerEvent
38 // Fired when a layer is added to this `FeatureGroup`
39 return this.fire('layeradd', {layer: layer});
40 },
41
42 removeLayer: function (layer) {
43 if (!this.hasLayer(layer)) {
44 return this;
45 }
46 if (layer in this._layers) {
47 layer = this._layers[layer];
48 }
49
50 layer.removeEventParent(this);
51
52 LayerGroup.prototype.removeLayer.call(this, layer);
53
54 // @event layerremove: LayerEvent
55 // Fired when a layer is removed from this `FeatureGroup`
56 return this.fire('layerremove', {layer: layer});
57 },
58
59 // @method setStyle(style: Path options): this
60 // Sets the given path options to each layer of the group that has a `setStyle` method.
61 setStyle: function (style) {
62 return this.invoke('setStyle', style);
63 },
64
65 // @method bringToFront(): this
66 // Brings the layer group to the top of all other layers
67 bringToFront: function () {
68 return this.invoke('bringToFront');
69 },
70
71 // @method bringToBack(): this
72 // Brings the layer group to the back of all other layers
73 bringToBack: function () {
74 return this.invoke('bringToBack');
75 },
76
77 // @method getBounds(): LatLngBounds
78 // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
79 getBounds: function () {
80 var bounds = new LatLngBounds();
81
82 for (var id in this._layers) {
83 var layer = this._layers[id];
84 bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
85 }
86 return bounds;
87 }
88});
89
90// @factory L.featureGroup(layers: Layer[])
91// Create a feature group, optionally given an initial set of layers.
92export var featureGroup = function (layers) {
93 return new FeatureGroup(layers);
94};