FeatureGroup
Quick answer
L.featureGroup extends LayerGroup with batch styling, combined bounds and event bubbling, so clicks on child layers arrive at the group as e.layer. Use it when a set of geometries must be restyled, framed or exported as one unit. L.geoJSON builds on this class, so both share the same batching behavior.
L.featureGroup( layers ?, options ?) → FeatureGroup
Key points
- setStyle applies path options to every vector child and silently ignores markers.
- getBounds merges child extents and can be handed straight to map.fitBounds.
- Child events bubble up with e.layer pointing at the clicked layer.
Example
var group = L.featureGroup().addTo(map);
var buildings = [
{ bounds: [[39.902, 116.388], [39.906, 116.394]], name: 'A 区' },
{ bounds: [[39.906, 116.394], [39.911, 116.401]], name: 'B 区' }
];
buildings.forEach(function (b) {
var rect = L.rectangle(b.bounds, { weight: 2, fillOpacity: 0.15 })
.bindPopup(b.name);
group.addLayer(rect);
});
/* 一次改所有面要素的样式 */
group.setStyle({ color: '#17694a', fillColor: '#22c55e' });
/* 子图层点击会冒泡到组,e.layer 是被点的那个 */
group.on('click', function (e) {
var id = L.Util.stamp(e.layer);
console.log('点击子图层', id);
});
map.fitBounds(group.getBounds(), { padding: [24, 24] });
Notes
- getBounds throws when a tile layer sits inside, because tile layers lack that method.
- Markers ignore setStyle, so restyling a mixed group only affects vector children.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). FeatureGroup. https://www.jingweizhi.com/en/leaflet/api/feature-group.html (accessed 2026-11-03).