Bird migration map with MapLibre GL JS

Swainson's Thrushes winter in Mexico, Central America, and South America and nest in the forests of Canada, Alaska, and the western mountains, so twice a year millions of them cross the United States, mostly at night.

Thousands of people now leave a microphone running in the yard, and BirdWeather's network of them names every bird it hears with BirdNET, a sound ID model from the Cornell Lab of Ornithology. The map plays 2025 week by week, coloring each square by the share of its stations that heard a Swainson's Thrush. Slide to any week, and click a square for its numbers.

Stations that heard one 0% 45%

Through the winter the map stays pale, since the thrushes are in Mexico and further south. The first ones turn up along the Gulf Coast in April, though few stations right on the coast heard one. The wave reaches Atlanta in early May, and Chicago, Minneapolis, and New York by mid-May, when a fifth to a third of their stations heard one, and Toronto late in May. Then it thins out as the birds settle in to nest in the north, except along the Pacific coast, where a separate population nests from California to Alaska: around Seattle, 4 in 10 stations heard one into July. From late August the wave runs back south, past Chicago and Toronto in mid-September and Atlanta at the end of the month, and by November the map is pale again.

Each square is 1.5° of latitude and longitude, and shows a week when at least three of its stations heard any bird that week. BirdNET names birds from a few seconds of sound, so it gets some wrong, and stations aren't spread evenly: there are about a hundred around Seattle and only a few in much of the Plains, where a square can swing from week to week. The weeks run from Sunday to Saturday, from January 5, 2025, to January 3, 2026.

Build it yourself

A Node.js script asks BirdWeather's API how many stations heard a Swainson's Thrush each week of spring 2025, in 3° squares of the lower 48 states, and a page colors the squares, with a slider to pick the week. It's the map above with bigger squares, for one season, without the playback. It was tested with MapLibre GL JS 6.15 in Chromium and Node.js 22.

What you need

  • Node.js 18 or later.
  • 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. BirdWeather's API needs no key.

Count the stations

BirdWeather's GraphQL API counts detections and stations for any box on the map and any stretch of days, and GraphQL lets one request hold many questions, each under its own name. Make a folder for the map, and in it a file called weeks.mjs:

weeks.mjs
import { writeFile } from "node:fs/promises";

const size = 3;
const start = Date.UTC(2025, 2, 2);
const weeks = 17;

async function ask(query) {
  const response = await fetch("https://app.birdweather.com/graphql", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ query }),
  });
  const { data, errors } = await response.json();
  if (errors) throw new Error(errors.map(({ message }) => message).join("; "));
  return data;
}

const { species } = await ask('{ species(scientificName: "Catharus ustulatus") { id } }');
const squares = [];
for (let lon = -126; lon < -66; lon += size) {
  for (let lat = 24; lat < 51; lat += size) squares.push({ lon, lat, heard: [], listening: [] });
}

const asks = [];
for (let week = 0; week < weeks; week++) {
  const from = new Date(start + week * 7 * 86400000).toISOString().slice(0, 10);
  const to = new Date(start + (week * 7 + 6) * 86400000).toISOString().slice(0, 10);
  for (const { lon, lat, heard, listening } of squares) {
    const where = `period: { from: "${from}", to: "${to}" }, sw: { lat: ${lat}, lon: ${lon} }, ne: { lat: ${lat + size}, lon: ${lon + size} }`;
    asks.push([heard, `counts(speciesId: "${species.id}", ${where}) { stations }`]);
    asks.push([listening, `counts(${where}) { stations }`]);
  }
}
for (let i = 0; i < asks.length; i += 200) {
  const batch = asks.slice(i, i + 200);
  const data = await ask(`{ ${batch.map(([, query], j) => `q${j}: ${query}`).join(" ")} }`);
  batch.forEach(([list], j) => list.push(data[`q${j}`].stations));
}

const features = [];
for (const { lon, lat, heard, listening } of squares) {
  if (!listening.some((count) => count >= 3)) continue;
  const properties = {};
  listening.forEach((count, week) => (properties[`w${week}`] = count >= 3 ? heard[week] / count : null));
  const ring = [[lon, lat], [lon + size, lat], [lon + size, lat + size], [lon, lat + size], [lon, lat]];
  features.push({ type: "Feature", properties, geometry: { type: "Polygon", coordinates: [ring] } });
}
await writeFile("squares.json", JSON.stringify({ type: "FeatureCollection", features }));
console.log(`Saved ${features.length} squares`);
  • counts with a speciesId tells how many stations in the box heard that bird in those days, and without one how many heard anything, which is how many were listening. The share of the two keeps a square full of stations from looking busier than one with a few.
  • Each square and week is two questions, so 17 weeks of 180 squares is 6,120. They go 200 to a request, named q0, q1, and so on, and each answer goes on the end of its square's list, so the lists stay in week order.
  • A square needs three stations listening in a week for its share to count, and at least one such week to be kept. Each week's share is saved as its own property, w0 to w16, so the page can pick a week with an expression.

Run it:

Terminal
node weeks.mjs

It sends 32 requests, which take about two minutes, then prints Saved 116 squares, or however many there are today, and writes squares.json.

Make the page

Next to squares.json, make 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>Swainson's Thrush migration</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"
        }
      }
    </script>
  </head>
  <body style="margin: 0">
    <label style="position: absolute; z-index: 1; top: 10px; left: 10px; padding: 6px 10px; background: white; font: 16px sans-serif">
      <span id="week"></span><br>
      <input id="slider" type="range" min="0" max="16" value="10" style="width: 220px">
    </label>
    <div id="map" style="height: 100vh"></div>
    <script type="module">
      import * as maplibregl from "maplibre-gl";

      const start = Date.UTC(2025, 2, 2);
      const map = new maplibregl.Map({
        container: "map",
        style: "https://api.mapricot.com/tiles/v1/styles/light.json?key=mapricot_pk_…",
        bounds: [
          [-126, 24],
          [-66, 51],
        ],
      });
      await map.once("load");

      map.addSource("squares", { type: "geojson", data: "squares.json", attribution: "Detections: BirdWeather, BirdNET" });
      map.addLayer({ id: "squares", type: "fill", source: "squares", paint: { "fill-opacity": 0.8 } });

      const slider = document.querySelector("#slider");
      function show() {
        const share = ["get", `w${slider.value}`];
        map.setFilter("squares", ["!=", share, null]);
        map.setPaintProperty("squares", "fill-color", [
          "interpolate", ["linear"], share,
          0, "#fff4e6", 0.15, "#fd7e14", 0.45, "#7c2d12",
        ]);
        const week = new Date(start + slider.value * 7 * 86400000);
        document.querySelector("#week").textContent = `Week of ${week.toLocaleDateString("en-US", { month: "long", day: "numeric", timeZone: "UTC" })}`;
      }
      slider.addEventListener("input", show);
      show();

      map.on("click", "squares", (event) => {
        const share = event.features[0].properties[`w${slider.value}`];
        new maplibregl.Popup().setLngLat(event.lngLat).setText(`${Math.round(share * 100)}% of stations heard one`).addTo(map);
      });
    </script>
  </body>
</html>
  • The fill layer draws every square, and show points it at the week the slider is on: setFilter hides squares with no share that week, and setPaintProperty colors the rest by it, from pale orange for none to dark brown for nearly half of the stations.
  • The slider starts on the week of May 11, when the birds are crossing the middle of the country. The date beside it is worked out from the start of the season, in UTC, so it reads the same in every time zone.
  • Clicking a square shows its share for the week on the slider.

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 the middle of the country in orange and brown. Slide back to March and forward to June to watch the color move north.

Swap the scientific name for another bird, such as Setophaga petechia for the Yellow Warbler, to follow its migration instead, and the start date to follow it in fall.

Data

  • Detections: BirdWeather, identified by BirdNET from the K. Lisa Yang Center for Conservation Bioacoustics at the Cornell Lab of Ornithology and Chemnitz University of Technology
  • Map: OpenStreetMap contributors (ODbL), in Mapricot's map tiles