Set dark mode based on system settings

This example shows how to change the map mode (light/dark) of the map based on the system settings.

The dark mode become more and more popular. To determine whether the system settings are normal or dark, we employ the matchMedia function that allows checking programmatically whether a CSS media query (prefers-color-scheme) has been fulfilled or not.

NPM module setup


npm install --save @maptiler/sdk bootstrap bootstrap-icons
import { Map, MapStyle, config } from '@maptiler/sdk';
import '@maptiler/sdk/dist/maptiler-sdk.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap-icons/font/bootstrap-icons.css';

config.apiKey = 'YOUR_MAPTILER_API_KEY_HERE';

let mediaQueryObj = window.matchMedia('(prefers-color-scheme: dark)');
let isDarkMode = mediaQueryObj.matches;

let activeMode = isDarkMode ? "dark" : "light";
const style = getStyleByMode(activeMode);
if (isDarkMode) {
  document.getElementById("modeSwitch").checked = true;
}

function getStyleByMode(mode) {
  return (mode == 'dark') ? MapStyle.DATAVIZ.DARK : MapStyle.DATAVIZ.LIGHT;
}

function switchMode(mode) {
  activeMode = mode;
  const style = getStyleByMode(mode);
  map.setStyle(style);
}

const map = new Map({
  container: 'map',
  style: getStyleByMode(activeMode),
  center: [2.31632, 48.86239],
  zoom: 6,
  hash: true
});

document.getElementById("modeSwitch").addEventListener('change', function() {
  if (this.checked && activeMode == "light") {
    switchMode("dark");
  } else if (!this.checked && activeMode == "dark") {
    switchMode("light");
  }
});
Change between light and dark mode based on the time of day

Change to dark mode at sunset

Examples

Toggle light and dark map modes based on time.

Switch to dark mode inside tunnels

Switch to dark mode inside tunnels

Examples

Change map style to dark mode when entering tunnels.

Built-in map styles

Built-in map styles

Tutorials

Easily create beautiful maps using reliable built-in styles.

Change map styles

Change map styles

Tutorials

Switch between built-in and custom map styles dynamically.

Was this helpful?