Skip to content
Agents tracked: 440 Downloads (7d): 202M down 19.5% GitHub stars: 10.4M Releases (7d): 607 Agent status: 3 with issuesSince last limit reset: Claude 28d · Codex 0d Updated Oct 21, 2026

Layer switcher and scale control in Leaflet

A layer switcher lets users turn groups of map data on and off, and a scale bar shows distances at the current zoom.

All Leaflet examples Leaflet: usage and stats

Layer switcher and scale control in Leaflet: screenshot of the example below running
The code below, running in Chromium on our server (Oct 12, 2026). Press Run to see it live and change it.

How it works

  1. Group layers. L.layerGroup collects related shapes: cafes, parks and bike routes. Two groups are added to the map at start; the routes are not. [1]
  2. Add the layer switcher. L.control.layers(null, overlays, { collapsed: false }) shows a checkbox for each overlay group, already expanded. [1]
  3. Add a scale bar and popups. L.control.scale().addTo(map) adds a scale bar control. Each cafe point also has bindPopup(), so clicking it shows the cafe name. [1]

Run and edit it

It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.

import * as L from 'leaflet';

const el = document.createElement('div');
el.style.cssText = 'position:fixed;inset:0;background:#1d2633';
document.getElementById('root').appendChild(el);

const map = L.map(el).setView([51.505, -0.09], 14);
const dot = (pos, name) => L.circleMarker(pos, { radius: 8, color: '#f6ae2d', fillOpacity: 0.9 }).bindPopup(name);

const cafes = L.layerGroup([
  dot([51.508, -0.1], 'Cafe Nero'),
  dot([51.503, -0.083], 'Corner Cafe'),
  dot([51.506, -0.07], 'Tea House'),
]).addTo(map);

const parks = L.layerGroup([
  L.polygon([[51.499, -0.115], [51.502, -0.1], [51.497, -0.095]], { color: '#81c995', fillOpacity: 0.4 }),
  L.circle([51.511, -0.085], { radius: 250, color: '#81c995', fillOpacity: 0.4 }),
]).addTo(map);

const routes = L.layerGroup([
  L.polyline([[51.496, -0.12], [51.504, -0.095], [51.5, -0.065]], { color: '#8ab4f8', weight: 5 }),
]);

L.control.layers(null, { Cafes: cafes, Parks: parks, 'Bike routes': routes }, { collapsed: false }).addTo(map);
L.control.scale().addTo(map);
Ctrl/⌘ + Enter runs

Free for signed-in members, with a daily limit. Describe the change in plain words; the new code runs only in your browser.

Tick and untick the boxes in the top-right control to show or hide each group. Code written by AgentGid [1].

Checked Oct 12, 2026: it starts without errors in Chromium with leaflet 1.9.4. Needs WebGL.

More Leaflet examples

Markers and popups in Leaflet GeoJSON layers in Leaflet Handling map clicks in Leaflet

Sources

  1. Leaflet website

Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.

Building something with Leaflet? Ask AgentGid →