Switch Vector Styles in MapLibre GL JS
MapLibre GL JSChange the map style at runtime using map.setStyle() to switch between MapTiler vector tile styles.
const map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/streets-v4/style.json?key=YOUR_MAPTILER_KEY',
center: [2.3522, 48.8566],
zoom: 12
});
map.addControl(new maplibregl.NavigationControl());
const styles = ['streets-v4', 'satellite', 'outdoor-v4', 'dataviz-dark'];
let idx = 0;
document.getElementById('switch-style').addEventListener('click', () => {
idx = (idx + 1) % styles.length;
map.setStyle(`https://api.maptiler.com/maps/${styles[idx]}/style.json?key=YOUR_MAPTILER_KEY`);
document.getElementById('switch-style').textContent = styles[idx];
});How it works
Calling map.setStyle() replaces the entire style including sources, layers, fonts, and sprites. MapTiler provides 16+ ready-made styles you can swap between at runtime.
After a style change, all custom sources and layers are removed. Listen for the styledata event to re-add them once the new style finishes loading.
The button cycles through four styles: streets, satellite, outdoor, and dataviz-dark.
Key APIs
| API | Description | Docs |
|---|---|---|
map.setStyle() |
Replace the current map style | maplibre.org docs |
map.on('styledata') |
Fires when a new style loads | maplibre.org docs |
FAQ
Do custom layers survive a style change?
No. Calling setStyle() removes all sources and layers. Listen for styledata or style.load and re-add your custom layers.
Can I use a custom style from MapTiler Cloud?
Yes. Replace the style path with your custom style ID from the MapTiler Cloud console.
Common mistakes
- Forgetting to re-add custom layers after
setStyle(): they are removed with the old style - Not using
map.once('styledata', ...)to wait for the new style before adding layers - Using deprecated style names like
streets-v2instead ofstreets-v4
Build maps using MapLibre GL JS with AI
Generate code like this switch vector styles in maplibre gl js example using the MapLibre GL JS skill in your IDE.
Related Examples
- Initialize a MapLibre GL JS Map
- Satellite Basemap with MapLibre GL JS
- See how to do this in Leaflet, MapTiler SDK or OpenLayers