首页 / Leaflet / API 文档
FeatureGroup
先看结论
带样式与范围能力的图层组,子图层的交互事件会向上冒泡到它。
L.featureGroup(layers?, options?) → FeatureGroup
参数
| 参数 | 默认值 | 说明 |
|---|---|---|
layers | [] | 初始图层数组,元素须是已创建的 Layer 实例 |
options.interactive | true | 组本身是否可交互;实际交互仍由子图层决定 |
options.bubblingMouseEvents | true | 子图层的鼠标事件是否冒泡到组 |
成员
| 成员 | 返回值 | 说明 |
|---|---|---|
setStyle(style) | this | 对组内所有矢量图层调用 setStyle,标记会被忽略 |
getBounds() | LatLngBounds | 所有子图层的并集范围,可用于 map.fitBounds |
getLayer(id) | Layer | 按 L.Util.stamp 生成的 id 取回子图层 |
addLayer(layer) / removeLayer(layer) | this | 增删子图层,组已在地图上时立即渲染 |
clearLayers() | this | 清空全部子图层 |
getLayers() | Layer[] | 子图层数组,可用于遍历修改 |
eachLayer(fn, context?) | this | 逐个回调,this 指向组 |
bringToFront() / bringToBack() | this | 整体调整绘制顺序 |
toGeoJSON(precision?) | FeatureCollection | 输出组内要素,precision 默认 6 位小数 |
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] });
FeatureGroup 与 LayerGroup 的差别只有三点:能批量设样式、能算总范围、
子图层事件会带着 e.layer 冒泡上来。不需要这些能力时用 LayerGroup 更轻。
getBounds() 依赖子图层的 getBounds 方法。标记、圆、
多段线、多边形、矩形、图片与视频叠加都实现了它;瓦片图层没有,混进同一个
FeatureGroup 会直接报错。只把几何要素放进组里,瓦片单独管理。
经纬志(2026)。《FeatureGroup》。https://www.jingweizhi.com/leaflet/api/feature-group.html(访问日期 2026-11-03)。