scripts/maps: bake maxspeed layer into v5 PMTiles generator (P5b posted speed limits)
- Commit
e556122025c55d60c57a4d21b42d8392ebc4aaa7- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-16 23:45 UTC (3 months ago)
- Parents
d59a755
Diff
scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdindex 172d29aab7..6fd547d3a0 100644--- a/scripts/maps/README.md+++ b/scripts/maps/README.md@@ -8,9 +8,10 @@ Builds the custom **`v5.pmtiles`** consumed by the `maps` app. This single file | `https://data.vayunmathur.com/v4.pmtiles` (base tiles) | `v5.pmtiles` base layers (identical schema) | | `maps/src/main/assets/admin0.fgb` + `admin1.fgb` (border masks) | `v5.pmtiles` `admin_country` / `admin_region` / `admin_city` layers | -On top of the base it also **bakes safety / road-furniture** data (speed+On top of the base it also **bakes** (a) safety / road-furniture data (speed cameras, ALPR/surveillance, stop signs, traffic signals) so the app never needs-a runtime Overpass query.+a runtime Overpass query, and (b) posted **speed limits** (`maxspeed`) for the+P5b speed-limit feature — all from the same file. > This directory is the **generator**. Running the full planet build is an infra > step (large + long-running); the scripts are designed to be correct, modular@@ -58,6 +59,7 @@ earth landcover landuse water roads buildings boundaries pois places | source-layer | geometry | key attributes | |---|---|---| | `safety` | Point | `kind` ∈ {`speed_camera`,`alpr`,`surveillance`,`stop_sign`,`traffic_signals`}, `name?`, `direction?`, `operator?`, `ref?`, `osm_id` |+| `maxspeed` | LineString/MultiLineString | **`maxspeed`** (raw OSM value, e.g. `"35 mph"`, `"50"`, `"50 km/h"`), `highway?`, `name?`, `osm_id` | | `admin_country` | Polygon/MultiPolygon | `admin_level=2`, `name`, `name_en`, **`ISO_A2`**, `iso_a3` | | `admin_region` | Polygon/MultiPolygon | `admin_level=4`, `name`, `name_en`, **`iso_3166_2`**, `country_iso` | | `admin_city` | Polygon/MultiPolygon | `admin_level=8`, `name`, `name_en` |@@ -66,6 +68,12 @@ The admin layers deliberately preserve `ISO_A2` (countries) and `iso_3166_2` (regions) — the same keys `CountryMap.kt` matches on — so P13 can repoint the mask lookup at the PMTiles source with **no attribute changes**. +The `maxspeed` layer feeds P5b's `MaxspeedSource`, which reads the posted speed+limit via `queryRenderedFeatures` on **source-layer `maxspeed`**, property+**`maxspeed`**. It is a dedicated layer (not an attribute on the base `roads`+layer) so it works whether the base is freshly built or the upstream Protomaps+base is reused verbatim. P13 points `MaxspeedSource.PMTILES_URL` at v5.pmtiles.+ --- ## Data sources & rationale@@ -81,6 +89,9 @@ mask lookup at the PMTiles source with **no attribute changes**. * `man_made=surveillance` (any other) → `surveillance` * `highway=stop` → `stop_sign` * `highway=traffic_signals` → `traffic_signals`+* **Maxspeed** — OpenStreetMap. Ways carrying a `maxspeed` (or+ `maxspeed:forward`/`maxspeed:backward`) tag; the raw value is kept verbatim so+ the app parses `mph`/`km/h`/bare numbers itself. * **Admin borders**: * country + region → **Natural Earth 10m** (`ne_10m_admin_0_countries`, `ne_10m_admin_1_states_provinces`). Chosen because the current `.fgb` are@@ -99,8 +110,10 @@ mask lookup at the PMTiles source with **no attribute changes**. | `build_v5_pmtiles.sh` | **Top-level orchestrator**: base + safety + admin → merge → `v5.pmtiles` | | `build_base_layers.sh` | Base tiles (Planetiler build **or** reuse upstream `v4.pmtiles`) | | `build_safety_layer.sh` | osmium → GeoJSON → `normalize_safety.py` → tippecanoe → `safety.pmtiles` |+| `build_maxspeed_layer.sh` | osmium → GeoJSON → `normalize_maxspeed.py` → tippecanoe → `maxspeed.pmtiles` | | `build_admin_layers.sh` | Natural Earth / OSM → `normalize_admin.py` → tippecanoe → `admin_*.pmtiles` | | `normalize_safety.py` | OSM tags → `safety` layer schema (pure stdlib, unit-tested) |+| `normalize_maxspeed.py` | OSM maxspeed ways → `maxspeed` layer schema (pure stdlib, unit-tested) | | `normalize_admin.py` | NE/OSM attrs → admin layer schema (pure stdlib, unit-tested) | | `test/test_normalize.py` | Dry-run unit test of the schema mapping (no external tools) | | `test/fixtures/*` | Tiny sample inputs for the test |@@ -173,8 +186,9 @@ Individual layers can also be built standalone — see each script's `--help`. | Artifact | Extent | Approx size | |---|---|---| | `safety.pmtiles` | planet | ~0.3–1 GB (point features only) |+| `maxspeed.pmtiles` | planet | ~1–3 GB (line features on tagged ways) | | `admin_country/region/city.pmtiles` | planet | ~50–300 MB combined |-| **`v5.pmtiles`** | planet | ≈ **137 GB** (dominated by the base; overlays add < 1%) |+| **`v5.pmtiles`** | planet | ≈ **137 GB** (dominated by the base; overlays add < 3%) | | `v5-sf.pmtiles` | one metro | tens of MB | The base dominates; the safety + admin overlays are a rounding error on top.@@ -225,11 +239,13 @@ passes: ``` $ python3 scripts/maps/test/test_normalize.py ...-26 passed, 0 failed+34 passed, 0 failed ``` -This validates: all five `kind` classifications (incl. DeFlock ALPR detection),-non-safety/non-point features dropped, `admin_level` mapping (2/4/8),-`ISO_A2` / `iso_3166_2` preservation, county-vs-city `admin_level` filtering, and-that every emitted line is valid GeoJSON (tippecanoe input). Run the metro dry-run above on a box with the toolchain installed for a full end-to-end check.+This validates: all five safety `kind` classifications (incl. DeFlock ALPR+detection), maxspeed value passthrough (mph/km/h/bare + `maxspeed:forward`+fallback, lines only), non-safety/non-point features dropped, `admin_level`+mapping (2/4/8), `ISO_A2` / `iso_3166_2` preservation, county-vs-city+`admin_level` filtering, and that every emitted line is valid GeoJSON+(tippecanoe input). Run the metro dry run above on a box with the toolchain+installed for a full end-to-end check.
scripts/maps/build_maxspeed_layer.sh
diff --git a/scripts/maps/build_maxspeed_layer.sh b/scripts/maps/build_maxspeed_layer.shnew file mode 100644index 0000000000..7de2947119--- /dev/null+++ b/scripts/maps/build_maxspeed_layer.sh@@ -0,0 +1,88 @@+#!/bin/bash+set -euo pipefail++# build_maxspeed_layer.sh — bake the `maxspeed` layer (posted speed limits)+#+# Produces a line-geometry PMTiles layer of OSM ways that carry a maxspeed tag,+# so the app's posted-speed-limit feature (P5b MaxspeedSource) can read it via+# queryRenderedFeatures from v5.pmtiles instead of a separate host.+#+# Source layer produced: maxspeed (attr: maxspeed, highway?, name?, osm_id)+# maxspeed = raw OSM value, e.g. "35 mph", "50", "50 km/h" (parsed app-side)+#+# Usage:+# ./build_maxspeed_layer.sh --pbf planet.osm.pbf --out maxspeed.pmtiles+# ./build_maxspeed_layer.sh --pbf planet.osm.pbf --bbox -122.6,37.2,-121.7,37.9 --out maxspeed.pmtiles+#+# Options:+# --pbf FILE Input OSM .pbf (required)+# --out FILE Output .pmtiles (default: maxspeed.pmtiles)+# --bbox BOX Optional "minlon,minlat,maxlon,maxlat" metro extract (dry runs)+# --minzoom N tippecanoe minzoom (default 12 — where roads appear)+# --maxzoom N tippecanoe maxzoom (default 16)+# --keep-tmp Don't delete intermediate files+#+# Tools required: osmium (osmium-tool), tippecanoe, python3++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PBF=""+OUT="maxspeed.pmtiles"+BBOX=""+MINZOOM=12+MAXZOOM=16+KEEP_TMP=0++while [[ $# -gt 0 ]]; do+ case "$1" in+ --pbf) PBF="$2"; shift 2 ;;+ --out) OUT="$2"; shift 2 ;;+ --bbox) BBOX="$2"; shift 2 ;;+ --minzoom) MINZOOM="$2"; shift 2 ;;+ --maxzoom) MAXZOOM="$2"; shift 2 ;;+ --keep-tmp) KEEP_TMP=1; shift ;;+ -h|--help) sed -n '4,30p' "$0" | sed 's/^# \?//'; exit 0 ;;+ *) echo "Unknown arg: $1" >&2; exit 1 ;;+ esac+done++[[ -n "$PBF" ]] || { echo "ERROR: --pbf required" >&2; exit 1; }+[[ -f "$PBF" ]] || { echo "ERROR: pbf not found: $PBF" >&2; exit 1; }+command -v osmium >/dev/null || { echo "ERROR: osmium-tool not installed" >&2; exit 1; }+command -v tippecanoe >/dev/null || { echo "ERROR: tippecanoe not installed" >&2; exit 1; }++TMP="$(mktemp -d)"+cleanup() { [[ "$KEEP_TMP" == "1" ]] || rm -rf "$TMP"; }+trap cleanup EXIT++SRC="$PBF"+if [[ -n "$BBOX" ]]; then+ echo "[maxspeed] extracting metro bbox $BBOX"+ osmium extract --overwrite -b "$BBOX" "$PBF" -o "$TMP/metro.osm.pbf"+ SRC="$TMP/metro.osm.pbf"+fi++echo "[maxspeed] filtering ways with a maxspeed tag"+osmium tags-filter --overwrite "$SRC" \+ w/maxspeed w/maxspeed:forward w/maxspeed:backward \+ -o "$TMP/maxspeed_raw.osm.pbf"++echo "[maxspeed] exporting to GeoJSON + normalizing"+osmium export -f geojsonseq --overwrite "$TMP/maxspeed_raw.osm.pbf" \+ | python3 "$HERE/normalize_maxspeed.py" \+ > "$TMP/maxspeed.geojsonseq"++FEATURES="$(wc -l < "$TMP/maxspeed.geojsonseq" | tr -d ' ')"+echo "[maxspeed] $FEATURES normalized feature(s)"+[[ "$FEATURES" -gt 0 ]] || echo "[maxspeed] WARNING: 0 features — check bbox/extract"++echo "[maxspeed] tiling -> $OUT (z$MINZOOM-$MAXZOOM)"+tippecanoe --force \+ -o "$OUT" \+ -l maxspeed \+ --minimum-zoom="$MINZOOM" \+ --maximum-zoom="$MAXZOOM" \+ --drop-densest-as-needed \+ --extend-zooms-if-still-dropping \+ "$TMP/maxspeed.geojsonseq"++echo "[maxspeed] done: $OUT"
scripts/maps/build_v5_pmtiles.sh
diff --git a/scripts/maps/build_v5_pmtiles.sh b/scripts/maps/build_v5_pmtiles.shindex 156ef78fab..1383597848 100644--- a/scripts/maps/build_v5_pmtiles.sh+++ b/scripts/maps/build_v5_pmtiles.sh@@ -5,6 +5,7 @@ set -euo pipefail # # v5.pmtiles = Protomaps base schema (unchanged, style.json-compatible) # + safety (baked road-furniture: cameras/ALPR/stops/signals)+# + maxspeed (posted speed limits for the P5b MaxspeedSource) # + admin_country / admin_region / admin_city (borders; replaces .fgb) # # This single file REPLACES both:@@ -14,8 +15,9 @@ set -euo pipefail # Pipeline (each step is a standalone script in this dir): # 1. build_base_layers.sh -> base.pmtiles (planetiler OR reuse v4) # 2. build_safety_layer.sh -> safety.pmtiles (osmium + tippecanoe)-# 3. build_admin_layers.sh -> admin_*.pmtiles (Natural Earth/OSM + tippecanoe)-# 4. tile-join -> v5.pmtiles (merge all layers)+# 3. build_maxspeed_layer.sh-> maxspeed.pmtiles (osmium + tippecanoe)+# 4. build_admin_layers.sh -> admin_*.pmtiles (Natural Earth/OSM + tippecanoe)+# 5. tile-join -> v5.pmtiles (merge all layers) # # Full planet build is the user's infra step (large + long). Prove correctness # first with a metro dry run:@@ -36,6 +38,7 @@ set -euo pipefail # --base-area A planetiler area name/path (base-mode build; default planet) # --skip-base don't (re)build base; expects <workdir>/base.pmtiles present # --skip-safety omit safety layer+# --skip-maxspeed omit maxspeed layer # --skip-admin omit admin layers # --keep-work keep intermediates #@@ -52,6 +55,7 @@ BASE_JAR="" BASE_AREA="planet" SKIP_BASE=0 SKIP_SAFETY=0+SKIP_MAXSPEED=0 SKIP_ADMIN=0 KEEP_WORK=0 @@ -66,9 +70,10 @@ while [[ $# -gt 0 ]]; do --base-area) BASE_AREA="$2"; shift 2 ;; --skip-base) SKIP_BASE=1; shift ;; --skip-safety) SKIP_SAFETY=1; shift ;;+ --skip-maxspeed) SKIP_MAXSPEED=1; shift ;; --skip-admin) SKIP_ADMIN=1; shift ;; --keep-work) KEEP_WORK=1; shift ;;- -h|--help) sed -n '4,55p' "$0" | sed 's/^# \?//'; exit 0 ;;+ -h|--help) sed -n '4,60p' "$0" | sed 's/^# \?//'; exit 0 ;; *) echo "Unknown arg: $1" >&2; exit 1 ;; esac done@@ -100,7 +105,16 @@ if [[ "$SKIP_SAFETY" == "0" ]]; then INPUTS+=("$WORK/safety.pmtiles") fi -# --- 3. admin ---+# --- 3. maxspeed ---+if [[ "$SKIP_MAXSPEED" == "0" ]]; then+ [[ -n "$PBF" ]] || { echo "ERROR: --pbf required for maxspeed layer (or --skip-maxspeed)" >&2; exit 1; }+ MS_ARGS=(--pbf "$PBF" --out "$WORK/maxspeed.pmtiles")+ [[ -n "$BBOX" ]] && MS_ARGS+=(--bbox "$BBOX")+ "$HERE/build_maxspeed_layer.sh" "${MS_ARGS[@]}"+ INPUTS+=("$WORK/maxspeed.pmtiles")+fi++# --- 4. admin --- if [[ "$SKIP_ADMIN" == "0" ]]; then ADMIN_ARGS=(--outdir "$WORK/admin") [[ -n "$PBF" ]] && ADMIN_ARGS+=(--pbf "$PBF")@@ -112,7 +126,7 @@ if [[ "$SKIP_ADMIN" == "0" ]]; then done fi -# --- 4. merge ---+# --- 5. merge --- echo "[v5] merging ${#INPUTS[@]} source(s) -> $OUT" printf ' + %s\n' "${INPUTS[@]}" # --no-tile-size-limit: don't drop features when combining dense base + overlays.@@ -123,7 +137,7 @@ echo "[v5] done: $OUT (${SIZE} bytes)" echo "" echo "Layers now in $OUT:" echo " base : earth landcover landuse water roads buildings boundaries pois places"-echo " new : safety admin_country admin_region admin_city"+echo " new : safety maxspeed admin_country admin_region admin_city" echo "" echo "Publish (bump key to v5.pmtiles):" echo " R2_KEY=v5.pmtiles ./scripts/maps/vendor_pmtiles.sh --local $OUT --source $OUT"
scripts/maps/normalize_maxspeed.py
diff --git a/scripts/maps/normalize_maxspeed.py b/scripts/maps/normalize_maxspeed.pynew file mode 100644index 0000000000..fce4f38736--- /dev/null+++ b/scripts/maps/normalize_maxspeed.py@@ -0,0 +1,110 @@+#!/usr/bin/env python3+"""normalize_maxspeed.py — build the `maxspeed` PMTiles layer from OSM ways.++P5b's MaxspeedSource (maps app) reads the posted speed limit by calling+queryRenderedFeatures on a vector source-layer named `maxspeed`, reading the+`maxspeed` property — the raw OSM maxspeed tag value, e.g. "35 mph", "50",+"50 km/h". We bake that into v5.pmtiles so the posted-speed-limit feature works+from the same file (no separate maxspeed.pmtiles host).++Reads GeoJSON (FeatureCollection or geojsonseq, e.g. from `osmium export`) of+highway ways carrying a `maxspeed` tag; writes geojsonseq with a minimal+schema: { maxspeed, highway?, name?, osm_id }. Line geometry only.++Usage:+ osmium tags-filter planet.osm.pbf w/maxspeed -o ms.osm.pbf+ osmium export -f geojsonseq ms.osm.pbf | python3 normalize_maxspeed.py > maxspeed.geojsonseq++Pure stdlib so it can run and be unit-tested without pyosmium/tippecanoe.+"""+from __future__ import annotations++import json+import sys+from typing import Any, Iterable, Iterator, Optional++LINE_TYPES = ("LineString", "MultiLineString")+++def extract_maxspeed(tags: dict[str, Any]) -> Optional[str]:+ """Return the maxspeed value to bake, or None to drop the feature.++ Keeps the raw OSM string (MaxspeedSource parses "mph"/"km/h"/bare number).+ Prefers the forward/backward-agnostic `maxspeed`; falls back to directional+ tags if only those exist.+ """+ for key in ("maxspeed", "maxspeed:forward", "maxspeed:backward"):+ val = tags.get(key)+ if val not in (None, ""):+ return str(val)+ return None+++def build_properties(maxspeed: str, tags: dict[str, Any], feature: dict[str, Any]) -> dict[str, Any]:+ props: dict[str, Any] = {"maxspeed": maxspeed}+ highway = tags.get("highway")+ if highway:+ props["highway"] = highway+ name = tags.get("name")+ if name:+ props["name"] = name+ osm_id = feature.get("id") or tags.get("@id") or tags.get("id") or tags.get("osm_id")+ if osm_id is not None:+ props["osm_id"] = str(osm_id)+ return props+++def iter_features(raw: str) -> Iterator[dict[str, Any]]:+ stripped = raw.lstrip()+ if stripped.startswith("{") and '"FeatureCollection"' in stripped[:200]:+ try:+ obj = json.loads(raw)+ if obj.get("type") == "FeatureCollection":+ yield from obj.get("features", [])+ return+ except json.JSONDecodeError:+ pass+ for line in raw.splitlines():+ line = line.strip().lstrip("\x1e").strip()+ if not line:+ continue+ try:+ obj = json.loads(line)+ except json.JSONDecodeError:+ continue+ if obj.get("type") == "Feature":+ yield obj+ elif obj.get("type") == "FeatureCollection":+ yield from obj.get("features", [])+++def normalize(features: Iterable[dict[str, Any]]) -> Iterator[dict[str, Any]]:+ for feature in features:+ geom = feature.get("geometry") or {}+ if geom.get("type") not in LINE_TYPES:+ continue+ tags = feature.get("properties") or {}+ maxspeed = extract_maxspeed(tags)+ if maxspeed is None:+ continue+ yield {+ "type": "Feature",+ "geometry": geom,+ "properties": build_properties(maxspeed, tags, feature),+ }+++def main(argv: list[str]) -> int:+ raw = sys.stdin.read()+ count = 0+ out = sys.stdout+ for feature in normalize(iter_features(raw)):+ out.write(json.dumps(feature, separators=(",", ":"), ensure_ascii=False))+ out.write("\n")+ count += 1+ sys.stderr.write(f"normalize_maxspeed: emitted {count} feature(s)\n")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))
scripts/maps/test/fixtures/maxspeed_sample.geojsonseq
diff --git a/scripts/maps/test/fixtures/maxspeed_sample.geojsonseq b/scripts/maps/test/fixtures/maxspeed_sample.geojsonseqnew file mode 100644index 0000000000..2ccc0da76b--- /dev/null+++ b/scripts/maps/test/fixtures/maxspeed_sample.geojsonseq@@ -0,0 +1,6 @@+{"type":"Feature","geometry":{"type":"LineString","coordinates":[[-122.42,37.77],[-122.41,37.78]]},"properties":{"highway":"residential","maxspeed":"25 mph","name":"Main St","id":"way/3001"}}+{"type":"Feature","geometry":{"type":"LineString","coordinates":[[-122.41,37.78],[-122.40,37.79]]},"properties":{"highway":"primary","maxspeed":"50","id":"way/3002"}}+{"type":"Feature","geometry":{"type":"MultiLineString","coordinates":[[[-122.40,37.79],[-122.39,37.80]]]},"properties":{"highway":"motorway","maxspeed":"100 km/h","id":"way/3003"}}+{"type":"Feature","geometry":{"type":"LineString","coordinates":[[-122.39,37.80],[-122.38,37.81]]},"properties":{"highway":"tertiary","maxspeed:forward":"30 mph","id":"way/3004"}}+{"type":"Feature","geometry":{"type":"LineString","coordinates":[[-122.38,37.81],[-122.37,37.82]]},"properties":{"highway":"service","id":"way/3005"}}+{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.37,37.82]},"properties":{"highway":"speed_camera","maxspeed":"40","id":"node/3006"}}
scripts/maps/test/test_normalize.py
diff --git a/scripts/maps/test/test_normalize.py b/scripts/maps/test/test_normalize.pyindex ee71e6b528..0cb7bb6d19 100644--- a/scripts/maps/test/test_normalize.py+++ b/scripts/maps/test/test_normalize.py@@ -22,6 +22,7 @@ FIX = HERE / "fixtures" sys.path.insert(0, str(ROOT)) import normalize_admin # noqa: E402+import normalize_maxspeed # noqa: E402 import normalize_safety # noqa: E402 @@ -92,6 +93,22 @@ def test_admin_region() -> None: check("MultiPolygon kept", feats[1]["geometry"]["type"] == "MultiPolygon") +def test_maxspeed() -> None:+ print("maxspeed layer:")+ raw = _load(FIX / "maxspeed_sample.geojsonseq")+ feats = list(normalize_maxspeed.normalize(normalize_maxspeed.iter_features(raw)))+ # 4 line features with maxspeed; service (no maxspeed) + Point node dropped.+ check("emits 4 line features", len(feats) == 4, f"got {len(feats)}")+ check("all line geometry", all(f["geometry"]["type"] in ("LineString", "MultiLineString") for f in feats))+ values = [f["properties"]["maxspeed"] for f in feats]+ check("keeps raw mph value", "25 mph" in values)+ check("keeps bare number value", "50" in values)+ check("keeps km/h value", "100 km/h" in values)+ check("falls back to maxspeed:forward", "30 mph" in values)+ check("every feature has maxspeed property", all(f["properties"].get("maxspeed") for f in feats))+ check("no point node leaked", all(f["geometry"]["type"] != "Point" for f in feats))++ def test_admin_city() -> None: print("admin_city layer:") raw = _load(FIX / "admin_city_sample.geojsonseq")@@ -114,6 +131,7 @@ def test_valid_geojson_output() -> None: def main() -> int: test_safety()+ test_maxspeed() test_admin_country() test_admin_region() test_admin_city()