Layers, layer groups and panes
Quick answer
This tutorial separates the four Leaflet containers: a single Layer, LayerGroup, FeatureGroup and GeoJSON, and explains when a group must behave as one object. It shows batch add and remove with addLayer, clearLayers and map.removeLayer, group-level click handling where e.layer identifies the child, and getBounds for fitting the view. It finishes with the default panes, their z-index values, and how createPane inserts a custom layer stack.
Key points
- Add a LayerGroup to the map once, then call addLayer on the group for each child.
- Bind click on a FeatureGroup and read e.layer to identify the clicked child layer.
- Create a custom pane with map.createPane and set its zIndex and pointerEvents.
Example
var group = L.layerGroup().addTo(map);
group.addLayer(L.marker([39.907359, 116.391263]));
group.addLayer(L.circle([39.907359, 116.391263], {
radius: 400,
color: '#17694a',
fillOpacity: 0.2
}));
group.clearLayers();
map.removeLayer(group);
group.addTo(map); // 再上线,之前清空的图层不会回来var stations = L.featureGroup([
L.marker([39.907359, 116.391263]).bindTooltip('天安门'),
L.marker([39.916345, 116.397155]).bindTooltip('王府井'),
L.marker([39.899000, 116.407000]).bindTooltip('前门')
]).addTo(map);
stations.on('click', function (e) {
var layer = e.layer; // 被点中的子图层
var ll = layer.getLatLng();
console.log(ll.lat, ll.lng);
});
map.fitBounds(stations.getBounds(), { padding: [24, 24] });
Notes
- clearLayers keeps the group but invalidates saved child references; re-add them explicitly.
- zIndex only orders siblings inside one pane, so it cannot reorder layers across panes.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). Layers, layer groups and panes. https://www.jingweizhi.com/en/leaflet/tutorials/layers-groups.html (accessed 2026-11-03).