Change between light and dark mode based on the time of day

This example demonstrates the process of altering the map display from a light to a dark mode, depending on the current time of day.

To achieve this, the MapTiler Geolocation API is utilized to acquire the user’s location data, while the SunCalc library is employed to compute the sunrise and sunset timings based on the user’s location.

NPM module setup


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

config.apiKey = 'YOUR_MAPTILER_API_KEY_HERE';
let map;
let activeMode = "light";
const now = new Date();
let times;

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

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

function timeFormat(time) {
  return time.toLocaleTimeString([], {
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
  });
}

function dateFromHours(hours) {
  const dateHours = new Date();
  const [h, m] = hours.split(":");
  dateHours.setHours(h, m);
  return dateHours;
}

function isDay(date) {
  return (date > times.sunriseEnd && date < times.sunset) ? true : false;
}

//call IP geolocation API see https://docs.maptiler.com/cloud/api/geolocation/
maptilersdk.geolocation.info()
.then((data) => {
  const userLngLat = [data.longitude, data.latitude];
  times = SunCalc.getTimes(now, data.latitude, data.longitude);
  document.getElementById('sun').innerText = timeFormat(times.sunriseEnd);
  document.getElementById('moon').innerText = timeFormat(times.sunset);
  document.getElementById('location').innerText = ` ${data.city}, ${data.country}`;
  document.getElementById('appt').value = timeFormat(now).substring(0,5);
  activeMode = isDay(now) ? 'light' : 'dark';
  
  map = map = new Map({
    container: 'map',
    style: getStyleByMode(activeMode),
    center: userLngLat,
    zoom: 12,
    hash: true
  });
});

document.getElementById("appt").addEventListener('change', function() {
  const hours = dateFromHours(this.value);
  if (isDay(hours) && activeMode == "dark") {
    switchMode("light");
  } else if (!isDay(hours) && activeMode == "light") {
    switchMode("dark");
  }
});
Set dark mode based on system settings

Set dark mode based on system settings

Examples

Switch map light/dark mode based on system color settings.

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?