Flood-hazard grades map by district
Colour Bangkok and Chiang Mai districts by real low, medium or high flood-hazard grades with a match expression, feature-state hover and a river or flash switch.
Intermediate
What you'll build
A choropleth of real flood-hazard grades per district for Bangkok (50 districts) and Chiang Mai (25). A dropdown switches province, a radio switch flips between river flood and flash flood, and hovering a district shows its Thai and English name, both grades and each grade's basis and confidence. The grades come from the Thai Properties Network region-statistics API and are vendored as two small GeoJSON files. They are terrain-modelled indicators, not a flood forecast and not calibrated against observed events. Serve the folder over http because the page fetches the files. Basemap tiles are MapScale, © OpenStreetMap contributors; the grades are modelled by Thai Properties Network from Copernicus DEM GLO-30 and OpenStreetMap.
cd docs/mapscale/visualizations/hazard-grades-map
python3 -m http.server 4202
# open http://localhost:4202/Create the page and a minimal basemap
A dark basemap (background, water, waterways, town labels) with the panel markup: province dropdown, hazard radios, legend and a caveat. Declare the grades GeoJSON source up front, empty, with promoteId: "id" so each district's id becomes its feature id; that is what feature-state hover addresses. Leave a gap in the layer list for the grades layers, above the basemap and below the labels.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Flood-hazard grades by district</title>
<style>
html,
body,
#map {
height: 100%;
margin: 0;
}
.panel {
position: absolute;
top: 12px;
left: 12px;
z-index: 1;
width: 250px;
max-width: calc(100% - 24px);
box-sizing: border-box;
padding: 12px;
border-radius: 10px;
background: rgba(8, 10, 16, 0.86);
color: #cfe7ff;
font: 13px/1.4 ui-monospace, monospace;
}
.panel select {
width: 100%;
}
.legend div {
display: flex;
align-items: center;
gap: 8px;
}
.legend i {
width: 22px;
height: 12px;
border: 1px solid rgba(255, 255, 255, 0.35);
}
#tip {
position: absolute;
z-index: 2;
display: none;
pointer-events: none;
width: 250px;
padding: 8px 10px;
border-radius: 8px;
background: rgba(8, 10, 16, 0.94);
color: #cfe7ff;
font: 12px/1.4 ui-monospace, monospace;
}
</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-hazard grades</strong>
<select id="province" aria-label="Province">
<option value="bangkok">Bangkok (50 districts)</option>
<option value="chiang-mai">Chiang Mai (25 districts)</option>
</select>
<label><input type="radio" name="hazard" value="river" checked /> River flood</label>
<label><input type="radio" name="hazard" value="flash" /> Flash flood</label>
<div id="legend-title">River flood</div>
<div class="legend" id="legend"></div>
<p>Terrain-modelled grades, not a flood forecast and not calibrated against observed events.</p>
</div>
<div id="tip"></div>
<script>
maplibregl.addProtocol("pmtiles", new pmtiles.Protocol().tile)
const EMPTY = { type: "FeatureCollection", features: [] }
const map = new maplibregl.Map({
container: "map",
center: [100.55, 13.75],
zoom: 9,
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",
},
grades: { type: "geojson", data: EMPTY, promoteId: "id" },
},
layers: [
{ id: "background", type: "background", paint: { "background-color": "#05070b" } },
{ id: "water", type: "fill", source: "ms", "source-layer": "water", paint: { "fill-color": "#0b2338" } },
{
id: "waterway", type: "line", source: "ms", "source-layer": "waterway",
paint: { "line-color": "#16436b", "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0.4, 14, 3] },
},
{
id: "place-labels", 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": 12 },
paint: { "text-color": "#cfe7ff", "text-halo-color": "#05070b", "text-halo-width": 1.4 },
},
],
},
})
map.on("load", () => {
// Steps 3 to 6 go here.
})
</script>
</body>
</html>Why the data is flat
The API nests grades in an estimates[] array, and style expressions can only read primitive properties of a feature, not arrays of objects. build-data.mjs therefore writes one plain property per hazard: riverLevel, riverBasis, riverConfidence, flashLevel, flashBasis, flashConfidence, plus id, th, en and handP10M (the district's 10th-percentile height above nearest drainage, in metres). A missing grade becomes the string unknown. These are the real properties of three districts: a Bangkok district with a modelled grade, a Chiang Mai district whose river grade is observed, and a Bangkok district with no estimate.
[
{
"id": 2, "th": "บางกะปิ", "en": "Bang Kapi",
"riverLevel": "high", "riverBasis": "modelled", "riverConfidence": "low",
"flashLevel": "low", "flashBasis": "modelled", "flashConfidence": "medium",
"handP10M": -1.3
},
{
"id": 592, "th": "เมืองเชียงใหม่", "en": "Mueang Chiang Mai",
"riverLevel": "high", "riverBasis": "observed", "riverConfidence": "high",
"flashLevel": "high", "flashBasis": "modelled", "flashConfidence": "medium",
"handP10M": -6.9
},
{
"id": 1, "th": "บางเขน", "en": "Bang Khen",
"riverLevel": "unknown", "riverBasis": "none", "riverConfidence": "none",
"flashLevel": "unknown", "flashBasis": "none", "flashConfidence": "none",
"handP10M": null
}
]Colour by grade with a match expression
match turns the string property into a colour; its last argument is the fallback for anything you did not list, which is how 'unknown' becomes neutral grey. The ramp is one sequential ColorBrewer YlOrRd scale: pale for low, deep red for high, so lightness alone orders the levels. Fill opacity and outline read feature-state hover, which is set in step 6.
const COLORS = { low: "#ffeda0", medium: "#fd8d3c", high: "#e31a1c", unknown: "#3a4252" }
const LEVEL_LABELS = { low: "Low", medium: "Medium", high: "High", unknown: "No estimate" }
const HAZARDS = {
river: { title: "River flood", prop: "riverLevel" },
flash: { title: "Flash flood", prop: "flashLevel" },
}
const colorBy = (prop) => [
"match", ["get", prop],
"low", COLORS.low,
"medium", COLORS.medium,
"high", COLORS.high,
COLORS.unknown,
]
map.addLayer({
id: "grades-fill",
type: "fill",
source: "grades",
paint: {
"fill-color": colorBy(HAZARDS.river.prop),
"fill-opacity": ["case", ["boolean", ["feature-state", "hover"], false], 0.92, 0.7],
},
}, "place-labels")
map.addLayer({
id: "grades-line",
type: "line",
source: "grades",
paint: {
"line-color": ["case", ["boolean", ["feature-state", "hover"], false], "#ffffff", "#0b0f18"],
"line-width": ["case", ["boolean", ["feature-state", "hover"], false], 2.5, 1],
},
}, "place-labels")Load a province and fit the camera
Fetch the province's file, hand it to the source with setData and fit the camera to the polygons' bounding box. The dropdown simply calls loadProvince again.
const PROVINCES = {
"bangkok": { file: "data/bangkok.geojson", name: "Bangkok" },
"chiang-mai": { file: "data/chiang-mai.geojson", name: "Chiang Mai" },
}
const boundsOf = (collection) => {
const b = new maplibregl.LngLatBounds()
const walk = (c) => (typeof c[0] === "number" ? b.extend(c) : c.forEach(walk))
for (const f of collection.features) { walk(f.geometry.coordinates) }
return b
}
let hoveredId = null
async function loadProvince(key) {
const res = await fetch(PROVINCES[key].file)
if (!res.ok) throw new Error("province request failed")
const data = await res.json()
hoveredId = null
map.getSource("grades").setData(data)
map.fitBounds(boundsOf(data), { padding: { top: 40, bottom: 80, left: 280, right: 40 }, duration: 0 })
}
document.getElementById("province").onchange = (e) => loadProvince(e.target.value)
loadProvince("bangkok")Switch hazard and add the hover tooltip
The hazard switch only swaps which property the same match expression reads, via setPaintProperty: no new layer and no data reload. Hover sets feature-state on the district under the mouse and clears it on mouseleave, and a small DOM card shows the name and both grades with their basis and confidence, because a grade without them would claim more than the model knows.
const legend = document.getElementById("legend")
function setHazard(key) {
const h = HAZARDS[key]
map.setPaintProperty("grades-fill", "fill-color", colorBy(h.prop))
document.getElementById("legend-title").textContent = h.title
legend.replaceChildren()
for (const level of ["low", "medium", "high", "unknown"]) {
const row = document.createElement("div")
const swatch = document.createElement("i")
swatch.style.background = COLORS[level]
row.append(swatch, LEVEL_LABELS[level])
legend.appendChild(row)
}
}
for (const radio of document.querySelectorAll("input[name=hazard]")) {
radio.onchange = () => setHazard(radio.value)
}
setHazard("river")
const tip = document.getElementById("tip")
const line = (label, level, basis, confidence) => {
const row = document.createElement("div")
const detail = basis === "none" ? "" : ` (${basis}, ${confidence} confidence)`
row.textContent = `${label}: ${LEVEL_LABELS[level]}${detail}`
return row
}
map.on("mousemove", "grades-fill", (e) => {
const f = e.features[0]
if (hoveredId !== null && hoveredId !== f.id) {
map.setFeatureState({ source: "grades", id: hoveredId }, { hover: false })
}
hoveredId = f.id
map.setFeatureState({ source: "grades", id: hoveredId }, { hover: true })
const p = f.properties
const title = document.createElement("b")
title.textContent = `${p.th} · ${p.en}`
tip.replaceChildren(
title,
line("River flood", p.riverLevel, p.riverBasis, p.riverConfidence),
line("Flash flood", p.flashLevel, p.flashBasis, p.flashConfidence),
)
tip.style.display = "block"
tip.style.left = `${Math.min(e.point.x + 14, window.innerWidth - 264)}px`
tip.style.top = `${Math.max(8, Math.min(e.point.y + 14, window.innerHeight - 110))}px`
})
map.on("mouseleave", "grades-fill", () => {
if (hoveredId !== null) { map.setFeatureState({ source: "grades", id: hoveredId }, { hover: false }) }
hoveredId = null
tip.style.display = "none"
})Refresh the data with build-data.mjs
data/build-data.mjs re-fetches both provinces from the public region-statistics API, flattens each feature as in step 3, rounds coordinates to 4 decimals and sorts by region id, so unchanged API data gives byte-identical files. Add a province by adding its parentProvinceId and file to PROVINCES in the script, and a matching entry in the page.
node docs/mapscale/visualizations/hazard-grades-map/data/build-data.mjs
# the public, read-only endpoint it calls, once per province (no key):
# GET https://api.thaipropertiesnetwork.com/region-statistics/risk-map?topic=flood-risk&parentProvinceId=1®ionType=district # Bangkok
# GET https://api.thaipropertiesnetwork.com/region-statistics/risk-map?topic=flood-risk&parentProvinceId=39®ionType=district # Chiang MaiLimitations, attribution and where to go next
Read the grades for what they are. They are terrain-modelled from Copernicus DEM GLO-30, height above nearest drainage (HAND), slope and distance to OpenStreetMap waterways: not a forecast, not calibrated against observed events. A modelled river-flood grade has low confidence because it summarises a district, not a point. Only Chiang Mai has observed-basis river-flood grades, from UNOSAT 2024 water extents. 20 of Bangkok's 50 districts have no estimate and are shown grey as 'No estimate'; the API does not say why. On a flat delta the HAND thresholds make every graded Bangkok district river-flood high, which is a statement about terrain, not about floods that happened or will happen. Keep the attribution on any page that shows these grades, and credit © OpenStreetMap contributors for the basemap.
<div class="badge">
Flood-hazard grades: terrain-modelled by Thai Properties Network from Copernicus DEM GLO-30 and
© OpenStreetMap contributors. Not a flood forecast. · Basemap: <a href="https://mapscale.io">MapScale</a>
</div>