Switch Tile Layers in Leaflet
LeafletSwitch between MapTiler raster styles at runtime by registering several L.tileLayer() basemaps in a Leaflet L.control.layers() switcher.
const streets = L.tileLayer('https://api.maptiler.com/maps/streets-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', {
tileSize: 256,
attribution: '© <a href="https://www.maptiler.com/">MapTiler</a> © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>'
});
const topo = L.tileLayer('https://api.maptiler.com/maps/topo-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', {
tileSize: 256,
attribution: '© <a href="https://www.maptiler.com/">MapTiler</a> © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>'
});
const map = L.map('map', { layers: [streets] }).setView([50.0755, 14.4378], 12);
L.control.layers({ 'Streets': streets, 'Topo': topo }).addTo(map); How to switch basemap layers in Leaflet
Leaflet’s L.control.layers() provides a built-in UI for switching between base layers. You create multiple L.tileLayer instances pointing to different MapTiler styles and pass them as base layers to the control. Only one base layer is visible at a time.
The first argument to L.control.layers() is an object of base layers (radio buttons). You can also pass a second argument for overlay layers (checkboxes) that stack on top. The map constructor’s layers option sets which layer is initially visible.
Key APIs
| API | Description | Docs |
|---|---|---|
L.tileLayer() |
Create raster tile layer | leafletjs.com/reference.html#tilelayer |
L.control.layers() |
Layer switcher control | leafletjs.com/reference.html#control-layers |
FAQ
How do I set the default style?
Pass the desired default layer in the map constructor’s layers array. The control will automatically select it.
Can I add more than two styles?
Yes. Add as many tile layers as you want to the base layers object, and each gets a radio button in the layer control.
Common mistakes
- Forgetting to include the default layer in the
layersoption ofL.map(), which leaves the map empty - Using deprecated style names like
streets-v2instead ofstreets-v4 - Adding the same layer to both base layers and overlays. It should be one or the other.
Build maps using Leaflet with AI
Generate code like this switch tile layers in leaflet example using the Leaflet skill in your IDE.
Related examples
- Initialize a Leaflet Map with MapTiler Tiles
- Satellite Basemap with Leaflet
- See how to do this in MapLibre GL JS, MapTiler SDK, or OpenLayers