Flood time-lapse from satellite observations
Step through real UNOSAT-observed flood extents from the 2021 floods with one GeoJSON source and a setFilter on the observation date.
Intermediate
What you'll build
A time-lapse of real satellite-observed flood extents from the September to November 2021 floods in central and north-eastern Thailand. Press play or drag the slider to step through the observation dates; a checkbox keeps earlier dates drawn dimmed underneath. The data is UNOSAT's observed water extents, delivered by the Thai Properties Network flood-history API and vendored in the example as one 1.4 MB GeoJSON file: 12 events, one MultiPolygon each. These are observed water extents on specific dates, not a forecast and not water depth, and there is no Bangkok coverage. The page fetches the file, so serve the folder over http. Basemap tiles are MapScale, © OpenStreetMap contributors. Flood extents are UNOSAT, CC BY-SA 4.0.
cd docs/mapscale/visualizations/flood-timelapse
python3 -m http.server 4201
# open http://localhost:4201/Create the page and a minimal basemap
One HTML file with a full-height map, a control panel (play button, date slider, date label, event list, a checkbox for earlier dates) and an attribution badge. The hand-built style over the public Thailand PMTiles archive needs no key: background, water, waterways, major roads and town labels. Keep the 'places' layer, because the flood layers are inserted beneath it. The badge carries the UNOSAT attribution and the licence, which you must keep.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Flood time-lapse</title>
<style>
html,
body,
#map {
height: 100%;
margin: 0;
}
.panel {
position: absolute;
top: 12px;
left: 12px;
z-index: 1;
width: 300px;
max-width: calc(100% - 48px);
padding: 12px;
border-radius: 10px;
background: rgba(8, 10, 16, 0.86);
color: #cfe7ff;
font: 13px/1.4 ui-monospace, monospace;
}
.row {
display: flex;
align-items: center;
gap: 8px;
}
#date {
flex: 1;
}
.badge {
position: absolute;
bottom: 12px;
left: 12px;
z-index: 1;
max-width: calc(100% - 24px);
padding: 6px 10px;
border-radius: 8px;
background: rgba(10, 13, 18, 0.85);
color: #cfe7ff;
font: 11px/1.4 ui-monospace, monospace;
}
.badge a {
color: #19d3ff;
}
</style>
<link rel="stylesheet" href="https://unpkg.com/maplibre-gl@5/dist/maplibre-gl.css" />
<script src="https://unpkg.com/maplibre-gl@5/dist/maplibre-gl.js"></script>
<script src="https://unpkg.com/pmtiles@4/dist/pmtiles.js"></script>
</head>
<body>
<div id="map"></div>
<div class="panel">
<strong>Flood time-lapse 2021</strong>
<p>Observed satellite water extents, not a forecast. Central and north-eastern Thailand, no Bangkok coverage.</p>
<div class="row">
<button id="play" type="button" aria-label="Play">▶</button>
<input id="date" type="range" min="0" max="0" step="1" value="0" aria-label="Observation date" />
</div>
<div id="date-label">Loading</div>
<ul id="events"></ul>
<label><input id="earlier" type="checkbox" checked /> Keep earlier dates (dim)</label>
</div>
<div class="badge">
Flood extents: UNOSAT / United Nations Satellite Centre,
<a href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a>, via Thai Properties Network flood history.
Observed satellite water extents, not a forecast.
Tiles: <a href="https://mapscale.io">MapScale</a> · © OpenStreetMap contributors
</div>
<script>
maplibregl.addProtocol("pmtiles", new pmtiles.Protocol().tile)
const map = new maplibregl.Map({
container: "map",
center: [101.5, 15.5],
zoom: 6,
minZoom: 4,
style: {
version: 8,
glyphs: "https://maps.thaipropertiesnetwork.com/{fontstack}/{range}.pbf",
sources: {
ms: {
type: "vector",
url: "pmtiles://https://maps.thaipropertiesnetwork.com/thailand-v2.pmtiles",
attribution: "© OpenStreetMap contributors · MapScale",
},
},
layers: [
{ id: "background", type: "background", paint: { "background-color": "#10151d" } },
{ id: "water", type: "fill", source: "ms", "source-layer": "water", paint: { "fill-color": "#0b1f33" } },
{
id: "waterway", type: "line", source: "ms", "source-layer": "waterway",
paint: { "line-color": "#12304d", "line-width": { base: 1.2, stops: [[6, 0.4], [12, 2]] } },
},
{
id: "roads", type: "line", source: "ms", "source-layer": "transportation", minzoom: 7,
filter: ["in", "class", "motorway", "trunk", "primary"],
paint: { "line-color": "#27324a", "line-width": { base: 1.2, stops: [[7, 0.4], [12, 1.5]] } },
},
{
id: "places", type: "symbol", source: "ms", "source-layer": "place",
filter: ["in", "class", "city", "town"],
layout: {
"text-field": ["coalesce", ["get", "name:en"], ["get", "name"]],
"text-font": ["Rubik Regular"],
"text-size": 11,
},
paint: { "text-color": "#8ea3bd", "text-halo-color": "#10151d", "text-halo-width": 1.4 },
},
],
},
})
map.addControl(new maplibregl.NavigationControl({ showCompass: false }), "top-right")
const slider = document.getElementById("date")
const playBtn = document.getElementById("play")
const earlier = document.getElementById("earlier")
const label = document.getElementById("date-label")
const list = document.getElementById("events")
// Steps 3 to 5 go here.
</script>
</body>
</html>Load the real GeoJSON and group it by date
Fetch the vendored file once and add it as a single geojson source. Each feature is one satellite observation with the properties eventKey, eventName, observedFrom and observedTo (plain YYYY-MM-DD strings) and floodAreaKm2. Group the properties by observedFrom to build the list of dates, set the slider's maximum, and fit the camera to the data's bounds computed from its coordinates.
let dates = []
const byDate = {}
map.on("load", async () => {
const res = await fetch("data/flood-extents-2021.geojson")
if (!res.ok) throw new Error("flood extents request failed")
const data = await res.json()
map.addSource("flood", { type: "geojson", data })
// Step 4 adds the three layers here.
for (const f of data.features) {
const d = f.properties.observedFrom
byDate[d] = byDate[d] ?? []
byDate[d].push(f.properties)
}
dates = Object.keys(byDate).sort()
slider.max = String(dates.length - 1)
const bounds = new maplibregl.LngLatBounds()
for (const f of data.features) {
for (const polygon of f.geometry.coordinates) {
for (const point of polygon[0]) { bounds.extend(point) }
}
}
map.fitBounds(bounds, { padding: { top: 40, bottom: 80, left: 340, right: 40 }, animate: false })
show(0)
})Three layers over one source
flood-before is a dim fill for earlier dates, flood-now a bright cyan fill for the chosen date and flood-outline a thin line. They share one source and differ only by filter and paint. Insert them under 'places' so town names stay readable. Add them right after addSource in the load handler.
map.addLayer({
id: "flood-before", type: "fill", source: "flood",
paint: { "fill-color": "#3a6ea5", "fill-opacity": 0.3 },
}, "places")
map.addLayer({
id: "flood-now", type: "fill", source: "flood",
paint: { "fill-color": "#19d3ff", "fill-opacity": 0.55 },
}, "places")
map.addLayer({
id: "flood-outline", type: "line", source: "flood",
paint: { "line-color": "#8cecff", "line-width": 0.6, "line-opacity": 0.8 },
}, "places")Animate with one filter expression
The whole time-lapse is map.setFilter. ISO dates compare correctly as strings, so ['==', ['get', 'observedFrom'], date] selects the current observation and ['<', ...] selects everything older, with no date parsing and no data reload. show() also fills the panel with each event's area in km² and name. The area is the API's figure for the full footprint. Play uses setInterval to advance the slider; touching the slider stops playback.
const fmt = (iso) =>
new Date(`${iso}T00:00:00Z`).toLocaleDateString("en-GB", {
day: "numeric", month: "short", year: "numeric", timeZone: "UTC",
})
function show(index) {
const date = dates[index]
map.setFilter("flood-now", ["==", ["get", "observedFrom"], date])
map.setFilter("flood-outline", ["==", ["get", "observedFrom"], date])
map.setFilter("flood-before", ["<", ["get", "observedFrom"], date])
label.textContent = fmt(date)
list.replaceChildren(
...byDate[date].map((p) => {
const li = document.createElement("li")
const range = p.observedTo === p.observedFrom ? "" : ` (${fmt(p.observedFrom)} to ${fmt(p.observedTo)})`
const b = document.createElement("b")
b.textContent = `${p.floodAreaKm2.toLocaleString("en-US")} km²`
li.append(b, ` · ${p.eventName}${range}`)
return li
}),
)
}
let timer = null
function stop() {
clearInterval(timer)
timer = null
playBtn.innerHTML = "▶"
}
playBtn.onclick = () => {
if (timer) { stop(); return }
if (Number(slider.value) >= dates.length - 1) { slider.value = 0; show(0) }
playBtn.innerHTML = "❚❚"
timer = setInterval(() => {
const next = Number(slider.value) + 1
if (next >= dates.length) { stop(); return }
slider.value = next
show(next)
}, 1400)
}
slider.oninput = () => { stop(); show(Number(slider.value)) }
earlier.onchange = () => {
map.setLayoutProperty("flood-before", "visibility", earlier.checked ? "visible" : "none")
}Refresh the data with build-data.mjs
data/build-data.mjs rebuilds the GeoJSON from the public flood-history API, no key needed, and is deterministic: two runs give a byte-identical file. It lists /events and keeps the events whose key starts with unosat-fl20210928tha-, fetches each /events/<eventKey>/footprint, keeps only features whose kind is flood, rounds coordinates to 4 decimals, drops repeated points and polygons (and holes) smaller than about 0.12 km², then writes one MultiPolygon per event sorted by observation date. That drops about 65 percent of the polygons to keep the file near 1.4 MB, so the drawn polygons cover slightly less than floodAreaKm2 says. One event whose polygons were all tiny (a 4.44 km² KOMPSAT-5 scene on 2021-10-06) disappears entirely. Lower MIN_AREA_DEG2 for more detail at the cost of file size.
bun docs/mapscale/visualizations/flood-timelapse/data/build-data.mjs
# the two public, read-only endpoints it calls (no key):
# GET https://api.thaipropertiesnetwork.com/flood-history/events
# GET https://api.thaipropertiesnetwork.com/flood-history/events/<eventKey>/footprintLimitations, licence and where to go next
Read the map for what it is. Each date is one satellite pass over its own footprint, so an area without polygons on a date was not mapped, not necessarily dry. Coverage is the UNOSAT assessment area in central, western and north-eastern Thailand: there is no Bangkok coverage and nothing from before 2021 here. The same API also lists 2024 events for Chiang Mai, Chiang Rai and Phayao that you could add by changing the key prefix in build-data.mjs. The data is licensed CC BY-SA 4.0: if you reuse or redistribute the file or anything derived from it, keep the attribution 'UNOSAT / United Nations Satellite Centre, CC BY-SA 4.0', state that it was modified, and share your adaptation under the same licence. Basemap credit is © OpenStreetMap contributors.
<div class="badge">
Flood extents: UNOSAT / United Nations Satellite Centre,
<a href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a>, via Thai Properties Network flood history.
Observed satellite water extents, not a forecast.
Tiles: <a href="https://mapscale.io">MapScale</a> · © OpenStreetMap contributors
</div>