---
title: "Change between light and dark mode based on the time of day | JavaScript maps SDK"
description: "Toggle light and dark map modes based on time."
---

> For AI agents: a documentation index is available at [/llms.txt](https://docs.maptiler.com/llms.txt). Markdown versions of all pages are available by appending .md to any URL.

# 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](https://docs.maptiler.com/cloud/api/geolocation/) is utilized to acquire the user’s location data, while the [SunCalc library](https://github.com/mourner/suncalc) is employed to compute the sunrise and sunset timings based on the user’s location.

### NPM module setup

```bash
npm install --save @maptiler/sdk suncalc bootstrap bootstrap-icons
```

#### main.js

```js
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");
  }
});
```

#### index.html

```html
<!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 the time of day</title>
  <link rel="stylesheet" href="./style.css">
</head>
<body>
  <div id="map">
  <div class="btns hero-card rounded-3 shadow-lg">
    <form>
      <div>
        <label for="appt" class="form-label">Select a time:</label>
        <input type="time" class="form-control" id="appt" name="appt">
      </div>
      <div class="mt-1">
        <div><i class="bi bi-geo-alt"></i></i><span id="location"></span></div>
      </div>
      <div class="hours mt-1">
        <div><i class="bi bi-sun"></i><span id="sun"></span></div>
        <div><i class="bi bi-moon"></i><span id="moon"></span></div>
      </div>
    </form>
  </div>
  </div>
  <script type="module" src="./main.js"></script>
</body>
</html>
```

#### style.css

```css
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;
}
.hours{
  display: flex;
  justify-content: space-around;
}
```

### Basic JavaScript setup

```html
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title>How to change the style (light/dark) of the map based on the time of day</title>
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
  <script src="https://cdn.maptiler.com/maptiler-sdk-js/v4.2.0/maptiler-sdk.umd.min.js"></script>
  <link href="https://cdn.maptiler.com/maptiler-sdk-js/v4.2.0/maptiler-sdk.css" rel="stylesheet" />
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
    rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
    crossorigin="anonymous" />
  <link rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/suncalc/1.9.0/suncalc.min.js"
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <style>
    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;
    }

    .hours {
      display: flex;
      justify-content: space-around;
    }
  </style>
</head>

<body>
  <div id="map">
    <div class="btns hero-card rounded-3 shadow-lg">
      <form>
        <div>
          <label for="appt" class="form-label">Select a time:</label>
          <input type="time" class="form-control" id="appt" name="appt">
        </div>
        <div class="mt-1">
          <div><i class="bi bi-geo-alt"></i></i><span id="location"></span></div>
        </div>
        <div class="hours mt-1">
          <div><i class="bi bi-sun"></i><span id="sun"></span></div>
          <div><i class="bi bi-moon"></i><span id="moon"></span></div>
        </div>
      </form>
    </div>
  </div>

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

    function getStyleByMode(mode) {
      return (mode == 'dark') ? maptilersdk.MapStyle.BASE.DARK : maptilersdk.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 maptilersdk.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");
      }
    });
  </script>
</body>

</html>
```

## Related examples

### [Set dark mode based on system settings](https://docs.maptiler.com/sdk-js/examples/style-by-settings/)

Examples

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

### [Switch to dark mode inside tunnels](https://docs.maptiler.com/sdk-js/examples/style-by-tunnel/)

Examples

Change map style to dark mode when entering tunnels.

### [Built-in map styles](https://docs.maptiler.com/sdk-js/examples/built-in-styles/)

Tutorials

Easily create beautiful maps using reliable built-in styles.

### [Change map styles](https://docs.maptiler.com/sdk-js/examples/change-map-styles/)

Tutorials

Switch between built-in and custom map styles dynamically.
