MapSnippets logoMapSnippets logo

Switch Vector Styles in OpenLayers

OpenLayers

Dynamically switch between MapTiler vector tile styles using ol-mapbox-style in OpenLayers.

progress_activityLoading map...
var currentMap;
function setStyle(styleName) {
  var url = 'https://api.maptiler.com/maps/' + styleName + '/style.json?key=YOUR_MAPTILER_KEY';
  var center = currentMap ? currentMap.getView().getCenter() : ol.proj.fromLonLat([2.3522, 48.8566]);
  var zoom = currentMap ? currentMap.getView().getZoom() : 12;
  document.getElementById('map').innerHTML = '';
  olms.apply('map', url).then(function(map) {
    map.getView().setCenter(center);
    map.getView().setZoom(zoom);
    currentMap = map;
  });
}
setStyle('streets-v4');

How it works

Switching vector styles in OpenLayers requires re-applying the style through ol-mapbox-style. The olms.apply() function replaces the map’s layers and sources with those defined in the new style.json.

Before switching, the current view center and zoom are saved so the map position is preserved. The map container is cleared, then olms.apply() creates a fresh map with the new style.

Key APIs

API Description Docs
olms.apply() Apply a MapTiler/Mapbox style to an element npmjs.com/package/ol-mapbox-style
map.getView().getCenter() Get current map center openlayers.org
map.getView().setZoom() Set zoom level openlayers.org

FAQ

Does switching styles lose my custom layers?

Yes. Since olms.apply() replaces the entire map, any custom layers or overlays must be re-added after the style switch.

Can I animate the transition between styles?

OpenLayers does not natively support style cross-fading. You can use CSS opacity transitions on the map container for a visual fade effect.

Common mistakes

  • Using deprecated style names like streets-v2: use streets-v4, outdoor-v4, topo-v4
  • Forgetting to preserve view state before clearing the map container
  • Not clearing the container before olms.apply(), which can stack multiple maps
auto_awesome

Build maps using OpenLayers with AI

Generate code like this switch vector styles in openlayers example using the OpenLayers skill in your IDE.