LayerGroup
Quick answer
L.layerGroup bundles multiple layers so they are added, removed and toggled as one entry, keeping the map and any layer control in sync with a single object. It is the lightweight option when you only need visibility management rather than styling or bounds.
L.layerGroup( layers? , options? ) → LayerGroup
Key points
- addLayer ignores layers already in the group, keeping membership idempotent.
- layeradd and layerremove events expose the affected layer as e.layer.
- setZIndex shifts the whole group within its pane.
Example
var group = L.layerGroup().addTo(map);
function addPoint(latlng, color) {
var dot = L.divIcon({
className: '',
html: '<i class="dot" style="background:' + color + '"></i>',
iconSize: [12, 12],
iconAnchor: [6, 6]
});
group.addLayer(L.marker(latlng, { icon: dot }));
}
addPoint([39.907359, 116.391263], '#1f5fd0');
group.on('layeradd', function (e) {
console.log('当前图层数', group.getLayers().length);
});
group.clearLayers();
Notes
- LayerGroup does not forward child clicks, so use FeatureGroup for group level interaction.
- Clearing the group while an external panel tracks state leaves its checkboxes out of sync.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). LayerGroup. https://www.jingweizhi.com/en/leaflet/api/layer-group.html (accessed 2026-11-03).