Shadow map with MapLibre GL JS

Pick a day of the year and a time of day, and every mountain and building on Earth casts its shadow, with night falling on the other side of the world. Look up any place, or drag with the right mouse button, or two fingers, to tilt and turn the map. Zoom in on a city to see its buildings' shadows too.

In Manhattan, the thin towers along 57th Street cast shadows a mile across Central Park at 3 on a November afternoon, but at noon in June the sun is so high that they don't reach the park at all. At the same time in November, the slopes below the Grand Canyon's South Rim are already in shadow. Zoom out to see where it's night: on the equinoxes, the line between day and night runs straight from pole to pole, and in December it leaves the Arctic in the dark all day.

The times are sun time at the map's center, so noon is when the sun is highest there. That's within an hour or so of the clock in most places, but further off on summer time or in a time zone made for somewhere else. The ground's shadows come from elevation data with points about 30 meters apart in most of the world, closer in the United States, so they leave out buildings and trees. Buildings' shadows come from their heights in OpenStreetMap, and fall as if the ground were flat. A building with no height in OpenStreetMap is drawn 10 meters tall, with a shadow to match.

Build it yourself

The tiles carry OpenStreetMap's building heights, so a page can work out each building's shadow from where the sun is. This one draws Midtown Manhattan in 3D with every building's shadow at the time you pick on a slider, today. It's the map above for buildings alone, without the ground's shadows, the night, or the day slider. It was tested with MapLibre GL JS 6.15 and SunCalc 1.9 in Chromium.

What you need

A web server to serve the page, and a browser key with the Map tiles product, made as API keys shows. Add http://localhost:* to its allowed origins, so it works from your computer while you build. Map tiles are free, and signing up takes a minute, with no credit card.

Make the page

Make a folder, and in it index.html, with your browser key in place of mapricot_pk_…:

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Shadows</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maplibre-gl@6.15.0/dist/maplibre-gl.css">
    <script type="importmap">
      {
        "imports": {
          "maplibre-gl": "https://cdn.jsdelivr.net/npm/maplibre-gl@6.15.0/+esm",
          "suncalc": "https://cdn.jsdelivr.net/npm/suncalc@1.9.0/+esm"
        }
      }
    </script>
  </head>
  <body style="margin: 0">
    <input id="time" type="range" min="420" max="1020" step="10" value="900" aria-label="Time of day" style="position: absolute; z-index: 1; top: 10px; left: 10px; width: 300px">
    <div id="map" style="height: 100vh"></div>
    <script type="module">
      import * as maplibregl from "maplibre-gl";
      import SunCalc from "suncalc";

      const map = new maplibregl.Map({
        container: "map",
        style: "https://api.mapricot.com/tiles/v1/styles/default.json?key=mapricot_pk_…",
        center: [-73.9765, 40.7695],
        zoom: 15,
        pitch: 50,
        bearing: 30,
      });
      await map.once("load");

      map.addSource("shadows", { type: "geojson", data: { type: "FeatureCollection", features: [] } });
      map.addLayer({
        id: "shadows",
        type: "fill-extrusion",
        source: "shadows",
        paint: { "fill-extrusion-color": "#1c2541", "fill-extrusion-height": 0, "fill-extrusion-opacity": 0.5 },
      });
      map.addLayer({
        id: "buildings-3d",
        type: "fill-extrusion",
        source: "protomaps",
        "source-layer": "buildings",
        paint: {
          "fill-extrusion-color": "#f8f4ec",
          "fill-extrusion-height": ["coalesce", ["get", "height"], 10],
          "fill-extrusion-base": ["coalesce", ["get", "min_height"], 0],
        },
      });

      function draw() {
        const { lng, lat } = map.getCenter();
        const today = new Date();
        const midnight = Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
        const date = new Date(midnight + (Number(time.value) - lng * 4) * 60000);
        const sun = SunCalc.getPosition(date, lat, lng);
        const shadows = [];
        if (sun.altitude > 0) {
          const length = 1 / Math.tan(sun.altitude);
          const east = Math.sin(sun.azimuth) * length / (111320 * Math.cos((lat * Math.PI) / 180));
          const north = Math.cos(sun.azimuth) * length / 110574;
          const buildings = map.querySourceFeatures("protomaps", { sourceLayer: "buildings", filter: ["==", "$type", "Polygon"] });
          for (const { geometry, properties } of buildings) {
            const height = properties.height ?? 10;
            const [dx, dy] = [east * height, north * height];
            const polygons = geometry.type === "Polygon" ? [geometry.coordinates] : geometry.coordinates;
            for (const [ring] of polygons) {
              shadows.push([ring]);
              for (let i = 1; i < ring.length; i++) {
                const [a, b] = [ring[i - 1], ring[i]];
                shadows.push([[a, b, [b[0] + dx, b[1] + dy], [a[0] + dx, a[1] + dy], a]]);
              }
            }
          }
        }
        map.getSource("shadows").setData({ type: "MultiPolygon", coordinates: shadows });
      }

      time.addEventListener("change", draw);
      map.on("moveend", () => map.once("idle", draw));
      map.once("idle", draw);
    </script>
  </body>
</html>
  • SunCalc gives the sun's height above the horizon, its altitude, and its direction, its azimuth, measured from south toward west, both in radians. Since the azimuth starts from south, its sine and cosine point the way a shadow falls: east and north.
  • The slider is in minutes after midnight, by the sun at the map's center: the sun crosses each line of longitude 4 minutes after the one to its east, so the page takes 4 minutes off for every degree east of Greenwich.
  • A shadow is 1 / tan(altitude) times as long as what casts it, so with the sun 15° up, a building's shadow is almost four times its height. east and north turn that into degrees of longitude and latitude per meter of height.
  • A building's shadow is its footprint swept along the shadow's length. That's the footprint, plus the four-sided band each wall's top edge sweeps out, from the wall to the end of the shadow.
  • The shadows layer is a 3D layer with no height, rather than a flat one, since a 3D layer's opacity applies to the layer as a whole, so where shadows overlap, as they do all over Manhattan, they're no darker.
  • querySourceFeatures only returns the buildings in the tiles on screen, so the page draws the shadows again each time the map stops moving and its tiles have loaded.

Open it

Serve the folder with npx serve or python3 -m http.server, and open the address it prints. Opened straight from the file, the map stays blank, as Open the page explains. You should see Midtown in 3D, and the towers on 57th Street casting long shadows across Central Park. Slide the time to watch them swing from west to east through the day. Each change takes a moment, since the page works out every building's shadow again.

Data

  • Ground heights: Terrain Tiles on AWS Open Data, made by Mapzen from ETOPO1 (NOAA), SRTM, GMTED2010, and 3DEP (USGS), and other national datasets, each credited in their attribution list
  • Buildings and their heights: OpenStreetMap contributors (ODbL), in Mapricot's map tiles
  • Place search: Mapricot's geocoding API
  • The sun's position: worked out in the page after the formulas in SunCalc (BSD 2-Clause)