MapSnippets logoMapSnippets logo

Switch Vector Styles in MapLibre GL JS

MapLibre GL JS

Change the map style at runtime using map.setStyle() to switch between MapTiler vector tile styles.

progress_activityLoading map...
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-v2 instead of streets-v4
auto_awesome

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.