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");
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>How to change the style (light/dark) of the map based on system settings</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div id="map">
<div class="btns hero-card rounded-3 shadow-lg">
<form>
<div class="">
<label class="form-label">Select mode</label>
</div>
<div class="d-flex">
<span class="me-1"><i class="bi bi-sun"></i></span>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" role="switch" id="modeSwitch">
<label class="form-check-label" for="modeSwitch"><i class="bi bi-moon"></i></label>
</div>
</div>
</form>
</div>
</div>
<script type="module" src="./main.js"></script>
</body>
</html>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
.btns {
z-index: 1000;
position: relative;
background-color: var(--bs-white);
width: fit-content;
padding: 10px;
}