Control.Layers
Quick answer
L.control.layers builds a panel with radio buttons for base layers and checkboxes for overlays, letting users switch basemaps and toggle thematic layers at runtime. Registered layers only appear in the interface; the control never adds them to the map by itself.
L.control.layers( baseLayers ?, overlays ?, options ?) → Control.Layers
Key points
- Base layer names follow object key order, so register the most common basemap first.
- addOverlay and addBaseLayer update the panel live without recreating the control.
- Listen for baselayerchange, overlayadd and overlayremove to react to user toggles.
Example
var osm = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap contributors'
});
var labels = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
opacity: 0.8,
maxZoom: 19
});
var city = L.layerGroup([
L.marker([39.907359, 116.391263]).bindPopup('天安门')
]);
var layers = L.control.layers(
{ 'OSM 标准': osm, 'OSM 淡色': labels },
{ '重点点位': city },
{ position: 'topright', collapsed: true }
).addTo(map);
map.addLayer(osm);
/* 运行时追加一个叠加层,复选框会自动出现 */
layers.addOverlay(
L.circle([39.907359, 116.391263], { radius: 800 }).bindPopup('1 km 覆盖'),
'覆盖范围'
);
/* 监听切换事件做联动 */
map.on('baselayerchange', function (e) { console.log('底图', e.name); });
map.on('overlayadd', function (e) { console.log('开启', e.name); });
Notes
- Layers passed to the control are listed but not displayed; call addTo on the map separately.
- collapsed true costs an extra click, so expand it when only two or three layers exist.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). Control.Layers. https://www.jingweizhi.com/en/leaflet/api/control-layers.html (accessed 2026-11-03).