Modern Apps git

← Modern-Apps.git

scripts/maps: bake OSM ma_pois layer + poi_names.bin + poi_index.bin

Commit
afe1987007eda0b90b5b71e5037d12c81bbe39bb
Author
vayun-mathur <[email protected]>
When
2026-08-18 04:07 UTC (3 months ago)
Parents
9b41506

Diff

scripts/maps/.gitignore
diff --git a/scripts/maps/.gitignore b/scripts/maps/.gitignoreindex a348c174b0..d60c7f544c 100644--- a/scripts/maps/.gitignore+++ b/scripts/maps/.gitignore@@ -1,5 +1,9 @@-*.pbf-*.pmtiles-map_data/-generator-ne/+*.pbf+*.pmtiles+map_data/+generator+poi_extract+poi_names.bin+poi_index.bin+*.geojsonseq+ne/
scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdindex 521de26e3d..e002c476ce 100644--- a/scripts/maps/README.md+++ b/scripts/maps/README.md@@ -66,6 +66,7 @@ earth  landcover  landuse  water  roads  buildings  boundaries  pois  places | `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` | | `transit_lines` | LineString/MultiLineString | **`kind`** ∈ {`rail`,`subway`,`light_rail`,`tram`,`monorail`,`train`}, `name?`, `ref?`, `colour?` (route colour, e.g. `"#DA291C"`), `osm_id` |+| `ma_pois` | Point | **`name`** (string), **`type`** (number, see POI type map), `osm_id` (number). OUR baked OSM POI layer — NOT the base `pois` layer. | | `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` |@@ -90,6 +91,17 @@ relations (named/coloured lines, kind from `route=*`), so a given corridor may b covered by both a way feature and a relation feature — filter on `colour`/`ref` presence if the app wants only the named route features. +The **`ma_pois`** layer is OUR own baked OSM POI layer — the P27 feature that+lets POI **placement / name / type** come from OpenStreetMap instead of a+runtime Google viewport scrape (Google is then hit only for rich details on+tap). It deliberately does **not** reuse the base Protomaps `pois` layer (which+the app suppresses). It is built by [`build_pois_layer.sh`](build_pois_layer.sh)+(→ [`poi_extract.cpp`](poi_extract.cpp)) at zooms **z12–z16**. The same pass also+emits two compact side files (`poi_names.bin` + `poi_index.bin`, formats below)+so the app can mmap + binary-scan POIs; the layer and the side files are+mutually consistent (same POI set, same coordinates). See+[POI layer & side files (P27)](#poi-layer--side-files-p27) below.+ ---  ## Data sources & rationale@@ -121,6 +133,19 @@ presence if the app wants only the named route features.     `multilinestrings` layer (`ogr2ogr`), whose `other_tags` HSTORE is parsed by     the normalizer to recover `route`/`colour`/`ref`. If `ogr2ogr` is not     installed the layer is still built from railway ways alone (colour omitted).+* **POIs (`ma_pois`)** — OpenStreetMap. Any node OR way/relation-area that has+  BOTH a `name` tag AND one of the recognised POI keys+  (`amenity`/`shop`/`tourism`/`leisure`/`office`/`healthcare`) becomes a POI. The+  tag value maps to a stable **type number** (see the [POI type map](#poi-type-map));+  a recognised key with an unmapped value falls into the `255` = "other" bucket.+  Way/relation geometry is reduced to a representative centroid (average of+  outer-ring node locations) so every POI renders as a point. Requiring a `name`+  naturally filters out unnamed street furniture (`amenity=bench`, etc.).+  Extraction is a single **libosmium** pass (`poi_extract.cpp`, matching the+  `generator.cpp` toolchain) — nodes are read directly and closed ways ++  multipolygon relations are assembled into areas via osmium's+  `MultipolygonManager`. The same pass emits the tile layer's geojsonseq AND the+  two side files, so all three are mutually consistent. * **Admin borders**:   * country + region → **Natural Earth 10m** (`ne_10m_admin_0_countries`,     `ne_10m_admin_1_states_provinces`). Chosen because the current `.fgb` are@@ -141,6 +166,8 @@ presence if the app wants only the named route features. | `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_transit_lines_layer.sh` | osmium + ogr2ogr → GeoJSON → `normalize_transit_lines.py` → tippecanoe → `transit_lines.pmtiles` |+| `build_pois_layer.sh` | g++ `poi_extract.cpp` → geojsonseq + `poi_names.bin` + `poi_index.bin` → tippecanoe → `ma_pois.pmtiles` |+| `poi_extract.cpp` | libosmium POI extractor: nodes + way/relation centroids → `ma_pois` geojsonseq + the two side files (full TYPE MAP + on-disk layouts in the file header) | | `build_admin_layers.sh` | Natural Earth / OSM → `normalize_admin.py` → tippecanoe → `admin_*.pmtiles` | | `publish_r2.sh` | Upload built `.pmtiles` to Cloudflare R2 (creds from env vars only) | | `normalize_safety.py` | OSM tags → `safety` layer schema (pure stdlib, unit-tested) |@@ -159,6 +186,8 @@ Full build needs (all are existing off-the-shelf tools — no C++ authored here) * **tippecanoe** ≥ 2.x (provides `tippecanoe` + `tile-join`, both write `.pmtiles`) * **osmium-tool** (`osmium`) * **GDAL** (`ogr2ogr`)+* **g++** (C++17) + **libosmium** headers — for the `ma_pois` extractor+  (`poi_extract.cpp`) and the routing-graph `generator.cpp` * **python3** (stdlib only) * Base build mode only: **Java 21** + the Protomaps basemap jar   (build once from `github.com/protomaps/basemaps`, `tiles/` → `mvn package`)@@ -220,6 +249,8 @@ Individual layers can also be built standalone — see each script's `--help`. | `safety.pmtiles` | planet | ~0.3–1 GB (point features only) | | `maxspeed.pmtiles` | planet | ~1–3 GB (line features on tagged ways) | | `transit_lines.pmtiles` | planet | ~0.2–1 GB (rail/transit line features) |+| `ma_pois.pmtiles` | planet | ~0.5–2 GB (named POI points) |+| `poi_names.bin` + `poi_index.bin` | planet | ~0.2–1 GB combined (side files) | | `admin_country/region/city.pmtiles` | planet | ~50–300 MB combined | | **`v5.pmtiles`** | planet | ≈ **137 GB** (dominated by the base; overlays add < 3%) | | `v5-sf.pmtiles` | one metro | tens of MB |@@ -300,6 +331,145 @@ to the `admin_country` / `admin_region` PMTiles layers (matching on `ISO_A2` /  --- +## POI layer & side files (P27)++`ma_pois` is the app's **own OSM POI layer**: POI placement, name and type come+from OpenStreetMap (baked here), so the app never scrapes a Google map viewport+to discover POIs — Google is queried only for rich details when the user taps a+POI. It is built by [`build_pois_layer.sh`](build_pois_layer.sh) →+[`poi_extract.cpp`](poi_extract.cpp) and merged into `v5.pmtiles` by+`build_v5_pmtiles.sh` (skip with `--skip-pois`). The **same** `poi_extract` pass+emits two compact side files **next to `--out`** so the app can `mmap` ++binary-scan POIs without opening the tileset:++```+poi_names.bin+poi_index.bin+```++Both are added to `run_generator.sh`'s R2 upload list so they ship from the same+`data.vayunmathur.com` host as the routing graph.++### `ma_pois` source-layer++| source-layer | geometry | attributes |+|---|---|---|+| `ma_pois` | Point (z12–z16) | **`name`** (string), **`type`** (number, see below), **`osm_id`** (number; negative for relation-sourced POIs) |++A POI = any node / closed-way area / multipolygon-relation area with a `name`+AND a recognised POI key (`amenity`/`shop`/`tourism`/`leisure`/`office`/+`healthcare`). Areas are reduced to a centroid point.++### POI type map++Stable POI type-number enum — **never renumber an existing value, only append**;+`255` is the catch-all "other". Kept in sync with `poi_extract.cpp` (source of+truth) and the app. Precedence when several keys are present:+`amenity` → `shop` → `tourism` → `leisure` → `office` → `healthcare`.++| # | type | example OSM tags |+|---|---|---|+| 0 | restaurant | `amenity=restaurant`/`food_court` |+| 1 | cafe | `amenity=cafe`/`ice_cream` |+| 2 | fast_food | `amenity=fast_food` |+| 3 | bar | `amenity=bar`/`pub`/`biergarten`/`nightclub` |+| 4 | shop (generic) | `shop=yes` and other unmapped `shop=*` |+| 5 | grocery | `shop=supermarket`/`convenience`/`greengrocer`/`grocery` |+| 6 | gas_station | `amenity=fuel` |+| 7 | pharmacy | `amenity=pharmacy`, `shop=chemist`, `healthcare=pharmacy` |+| 8 | hotel | `tourism=hotel`/`motel`/`hostel`/`guest_house`/`apartment` |+| 9 | bank | `amenity=bank`/`atm`/`bureau_de_change` |+| 10 | hospital | `amenity=hospital`/`clinic`, `healthcare=hospital`/`clinic` |+| 11 | school | `amenity=school`/`college`/`university`/`kindergarten`/`language_school`/`driving_school` |+| 12 | park | `leisure=park`/`garden`/`nature_reserve` |+| 13 | gym | `leisure=fitness_centre`/`sports_centre` |+| 14 | place_of_worship | `amenity=place_of_worship` |+| 15 | attraction | `tourism=attraction`/`theme_park`/`zoo`/`viewpoint`/`artwork`/`gallery`/`aquarium` |+| 16 | parking | `amenity=parking`/`parking_entrance`/`bicycle_parking` |+| 17 | cinema | `amenity=cinema` |+| 18 | theatre | `amenity=theatre`/`arts_centre` |+| 19 | library | `amenity=library` |+| 20 | post_office | `amenity=post_office` |+| 21 | police | `amenity=police` |+| 22 | fire_station | `amenity=fire_station` |+| 23 | townhall | `amenity=townhall`/`courthouse`, `office=government` |+| 24 | clothing | `shop=clothes`/`shoes`/`boutique`/`fashion`/`tailor` |+| 25 | electronics | `shop=electronics`/`mobile_phone`/`computer`/`hifi` |+| 26 | hardware | `shop=hardware`/`doityourself`/`trade`/`paint` |+| 27 | beauty | `shop=hairdresser`/`beauty` |+| 28 | car | `shop=car`/`car_repair`/`car_parts`/`tyres`, `amenity=car_rental`/`car_wash`/`car_sharing` |+| 29 | bakery | `shop=bakery` |+| 30 | books | `shop=books`/`stationery` |+| 31 | furniture | `shop=furniture`/`interior_decoration`/`houseware` |+| 32 | sports_shop | `shop=sports`/`outdoor`/`bicycle` |+| 33 | department_store | `shop=department_store`/`mall` |+| 34 | dentist | `amenity=dentist`, `healthcare=dentist` |+| 35 | doctor | `amenity=doctors`, `healthcare=doctor`/`centre` |+| 36 | veterinary | `amenity=veterinary`, `healthcare=veterinary` |+| 37 | charging_station | `amenity=charging_station` |+| 38 | museum | `tourism=museum` |+| 39 | office (generic) | other unmapped `office=*` |+| 40 | tourism_info | `tourism=information` |+| 41 | florist | `shop=florist` |+| 42 | jewelry | `shop=jewelry`/`jewellery` |+| 43 | optician | `shop=optician`, `healthcare=optometrist` |+| 44 | laundry | `shop=laundry`/`dry_cleaning` |+| 45 | pet | `shop=pet` |+| 46 | liquor | `shop=alcohol`/`wine`/`beverages` |+| 47 | toys | `shop=toys` |+| 48 | gift | `shop=gift` |+| 49 | marketplace | `amenity=marketplace` |+| 255 | other | any recognised POI key with an unmapped value |++### `poi_names.bin` — deduped name table++Each **unique** name is stored **once**, UTF-8, **NUL-terminated**, concatenated+in first-seen order:++```+"Blue Bottle Coffee\0Philz Coffee\0Dolores Park\0…"+```++A **"name start index"** (the `name_off` field in `poi_index.bin`) is the **byte+offset** of the name's first byte. To read a name: seek to `name_off` and read+bytes up to (not including) the next `0x00`. Multiple POIs with an identical name+share the same offset (that is the dedup win). Offsets are `uint32` byte offsets+(the table is well under 4 GB for a planet build).++### `poi_index.bin` — flat fixed-size records++A flat array of fixed **14-byte**, **little-endian**, packed records — one per+POI, in the SAME order as the `ma_pois` features:++| field | type | bytes | meaning |+|---|---|---|---|+| `lat_e7` | `int32` | 0–3 | latitude × 1e7 |+| `lon_e7` | `int32` | 4–7 | longitude × 1e7 |+| `name_off` | `uint32` | 8–11 | byte offset into `poi_names.bin` |+| `type` | `uint16` | 12–13 | POI type number (see the type map) |++`record_count = filesize(poi_index.bin) / 14`. Records are **sorted ascending by+the 64-bit Z-order (Morton) key of (lat, lon)** — computed exactly as+`generator.cpp`'s `latlng_to_spatial` (interleave the 32-bit normalized+`x=(lon+180)/360`, `y=(lat+90)/180`) — giving spatial locality for range scans.+The Morton key itself is **not** stored; the app recomputes it from `lat_e7`/+`lon_e7` when needed. Both files are byte-for-byte reproducible for a given input.++C/Rust view of a record:++```c+#pragma pack(push, 1)+struct PoiRecord {   // 14 bytes, little-endian+    int32_t  lat_e7;+    int32_t  lon_e7;+    uint32_t name_off;   // offset into poi_names.bin+    uint16_t type;+};+#pragma pack(pop)+```++---+ ## Single global routing graph (P16)  The offline **routing graph** is a **single global graph** — there is no@@ -391,3 +561,27 @@ 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.++### P27 `ma_pois` dry run (toolchain box)++The POI layer + side files were validated end-to-end on a box with the full+toolchain (libosmium 2.20, osmium, tippecanoe, pmtiles) against the California+extract clipped to a small SF bbox (`-122.44,37.76,-122.40,37.80`):++```+$ ./build_pois_layer.sh --pbf california-latest.osm.pbf \+      --bbox -122.44,37.76,-122.40,37.80 \+      --out ma_pois.pmtiles --names-out poi_names.bin --index-out poi_index.bin+[poi] extracted 5918 POI(s)+[poi] wrote 5392 unique name(s), 5918 record(s)+[poi]   poi_names.bin (96408 bytes)+[poi]   poi_index.bin (82852 bytes)   # 5918 × 14+[ma_pois] tiling -> ma_pois.pmtiles (z12-16)+```++Verified: `poi_extract.cpp` compiles clean; `ma_pois` appears in the tileset at+**z12–16** (and coexists with other layers after `tile-join` — a merge with+`safety.pmtiles` lists both `ma_pois` and `safety`); each tiled feature carries+`name`/`type`/`osm_id`; `poi_index.bin` records decode back to the exact+`ma_pois` features (Morton-sorted); and POIs sharing a name resolve to the same+`poi_names.bin` offset (212 shared offsets in the sample), confirming dedup.
scripts/maps/build_pois_layer.sh
diff --git a/scripts/maps/build_pois_layer.sh b/scripts/maps/build_pois_layer.shnew file mode 100644index 0000000000..77848cc1aa--- /dev/null+++ b/scripts/maps/build_pois_layer.sh@@ -0,0 +1,107 @@+#!/bin/bash+set -euo pipefail++# build_pois_layer.sh — bake our OWN OSM POI layer (`ma_pois`) + two side files.+#+# So that POI placement/name/type come from OpenStreetMap (baked at build time),+# not a runtime Google viewport scrape. Google is then hit only for rich details+# when the user taps a POI. This deliberately does NOT reuse the Protomaps base+# `pois` layer (the app suppresses that one).+#+# Produces three mutually-consistent outputs from a single `poi_extract` pass+# (same POI set, same coordinates):+#+#   * <out>.pmtiles   source-layer `ma_pois` (Point) — attrs: name, type, osm_id+#   * poi_names.bin   deduped NUL-terminated UTF-8 name table (each unique name+#                     once); a "name start index" is the byte offset of a name+#   * poi_index.bin   flat 14-byte records (little-endian):+#                       int32 lat_e7, int32 lon_e7, uint32 name_off, uint16 type+#                     sorted by Morton (Z-order) key of (lat,lon)+#+# See poi_extract.cpp for the full TYPE MAP + the exact on-disk layouts, and the+# README (`ma_pois` schema + file formats) for the app-side contract.+#+# Usage:+#   ./build_pois_layer.sh --pbf planet.osm.pbf --out ma_pois.pmtiles+#   ./build_pois_layer.sh --pbf planet.osm.pbf --bbox -122.6,37.2,-121.7,37.9 \+#       --out ma_pois.pmtiles --names-out poi_names.bin --index-out poi_index.bin+#+# Options:+#   --pbf FILE        Input OSM .pbf (required)+#   --out FILE        Output .pmtiles (default: ma_pois.pmtiles)+#   --names-out FILE  Output name table (default: poi_names.bin)+#   --index-out FILE  Output record index (default: poi_index.bin)+#   --bbox BOX        Optional "minlon,minlat,maxlon,maxlat" metro extract (dry runs)+#   --minzoom N       tippecanoe minzoom (default 12)+#   --maxzoom N       tippecanoe maxzoom (default 16)+#   --keep-tmp        Don't delete intermediate files+#+# Tools required: g++ (C++17) + libosmium headers, osmium (osmium-tool), tippecanoe++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PBF=""+OUT="ma_pois.pmtiles"+NAMES_OUT="poi_names.bin"+INDEX_OUT="poi_index.bin"+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 ;;+        --names-out) NAMES_OUT="$2"; shift 2 ;;+        --index-out) INDEX_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,40p' "$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 g++        >/dev/null || { echo "ERROR: g++ not installed" >&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++echo "[ma_pois] compiling poi_extract"+g++ -O3 -std=c++17 "$HERE/poi_extract.cpp" -o "$TMP/poi_extract" \+    -lz -lexpat -lbz2 -pthread++SRC="$PBF"+if [[ -n "$BBOX" ]]; then+    echo "[ma_pois] extracting metro bbox $BBOX"+    osmium extract --overwrite -b "$BBOX" "$PBF" -o "$TMP/metro.osm.pbf"+    SRC="$TMP/metro.osm.pbf"+fi++echo "[ma_pois] extracting POIs -> geojsonseq + $NAMES_OUT + $INDEX_OUT"+"$TMP/poi_extract" "$SRC" \+    --geojson "$TMP/ma_pois.geojsonseq" \+    --names "$NAMES_OUT" \+    --index "$INDEX_OUT"++FEATURES="$(wc -l < "$TMP/ma_pois.geojsonseq" | tr -d ' ')"+echo "[ma_pois] $FEATURES POI feature(s)"+[[ "$FEATURES" -gt 0 ]] || echo "[ma_pois] WARNING: 0 features — check bbox/extract"++echo "[ma_pois] tiling -> $OUT (z$MINZOOM-$MAXZOOM)"+tippecanoe --force \+    -o "$OUT" \+    -l ma_pois \+    --minimum-zoom="$MINZOOM" \+    --maximum-zoom="$MAXZOOM" \+    --drop-densest-as-needed \+    --extend-zooms-if-still-dropping \+    "$TMP/ma_pois.geojsonseq"++echo "[ma_pois] done: $OUT + $NAMES_OUT + $INDEX_OUT"
scripts/maps/build_v5_pmtiles.sh
diff --git a/scripts/maps/build_v5_pmtiles.sh b/scripts/maps/build_v5_pmtiles.shindex 33ee707cf3..62f6227312 100644--- a/scripts/maps/build_v5_pmtiles.sh+++ b/scripts/maps/build_v5_pmtiles.sh@@ -7,8 +7,13 @@ set -euo pipefail #            + safety     (baked road-furniture: cameras/ALPR/stops/signals) #            + maxspeed   (posted speed limits for the P5b MaxspeedSource) #            + transit_lines (OSM rail/subway/tram/… lines for the P22 highlight)+#            + ma_pois    (OUR baked OSM POI layer: placement/name/type from OSM) #            + admin_country / admin_region / admin_city  (borders; replaces .fgb) #+# The ma_pois step ALSO emits two compact side files next to --out+# (poi_names.bin + poi_index.bin) that the app mmaps for POI lookup — see+# build_pois_layer.sh / poi_extract.cpp / README for the exact formats.+# # This single file REPLACES both: #   * https://data.vayunmathur.com/v4.pmtiles      (base tiles) #   * maps/src/main/assets/admin0.fgb + admin1.fgb (border masks)@@ -18,8 +23,9 @@ set -euo pipefail #   2. build_safety_layer.sh  -> safety.pmtiles         (osmium + tippecanoe) #   3. build_maxspeed_layer.sh-> maxspeed.pmtiles       (osmium + tippecanoe) #   4. build_transit_lines_layer.sh -> transit_lines.pmtiles (osmium/ogr2ogr + tippecanoe)-#   5. build_admin_layers.sh  -> admin_*.pmtiles        (Natural Earth/OSM + tippecanoe)-#   6. tile-join              -> v5.pmtiles             (merge all layers)+#   5. build_pois_layer.sh    -> ma_pois.pmtiles + poi_names.bin + poi_index.bin+#   6. build_admin_layers.sh  -> admin_*.pmtiles        (Natural Earth/OSM + tippecanoe)+#   7. 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:@@ -42,6 +48,7 @@ set -euo pipefail #   --skip-safety     omit safety layer #   --skip-maxspeed   omit maxspeed layer #   --skip-transit-lines omit transit_lines layer+#   --skip-pois       omit ma_pois layer + poi_names.bin/poi_index.bin side files #   --skip-admin      omit admin layers #   --publish         after a successful build, upload $OUT to R2 (publish_r2.sh; #                     reads R2_ENDPOINT/R2_ACCESS_KEY_ID/R2_SECRET_ACCESS_KEY from env)@@ -63,6 +70,7 @@ SKIP_BASE=0 SKIP_SAFETY=0 SKIP_MAXSPEED=0 SKIP_TRANSIT_LINES=0+SKIP_POIS=0 SKIP_ADMIN=0 KEEP_WORK=0 PUBLISH=0@@ -81,6 +89,7 @@ while [[ $# -gt 0 ]]; do         --skip-safety) SKIP_SAFETY=1; shift ;;         --skip-maxspeed) SKIP_MAXSPEED=1; shift ;;         --skip-transit-lines) SKIP_TRANSIT_LINES=1; shift ;;+        --skip-pois) SKIP_POIS=1; shift ;;         --skip-admin) SKIP_ADMIN=1; shift ;;         --keep-work) KEEP_WORK=1; shift ;;         --publish) PUBLISH=1; shift ;;@@ -135,7 +144,18 @@ if [[ "$SKIP_TRANSIT_LINES" == "0" ]]; then     INPUTS+=("$WORK/transit_lines.pmtiles") fi -# --- 5. admin ---+# --- 5. ma_pois (our baked OSM POI layer + poi_names.bin/poi_index.bin) ---+if [[ "$SKIP_POIS" == "0" ]]; then+    [[ -n "$PBF" ]] || { echo "ERROR: --pbf required for ma_pois layer (or --skip-pois)" >&2; exit 1; }+    OUTDIR="$(cd "$(dirname "$OUT")" && pwd)"+    POIS_ARGS=(--pbf "$PBF" --out "$WORK/ma_pois.pmtiles" \+        --names-out "$OUTDIR/poi_names.bin" --index-out "$OUTDIR/poi_index.bin")+    [[ -n "$BBOX" ]] && POIS_ARGS+=(--bbox "$BBOX")+    "$HERE/build_pois_layer.sh" "${POIS_ARGS[@]}"+    INPUTS+=("$WORK/ma_pois.pmtiles")+fi++# --- 6. admin --- if [[ "$SKIP_ADMIN" == "0" ]]; then     ADMIN_ARGS=(--outdir "$WORK/admin")     [[ -n "$PBF" ]] && ADMIN_ARGS+=(--pbf "$PBF")@@ -147,7 +167,7 @@ if [[ "$SKIP_ADMIN" == "0" ]]; then     done fi -# --- 6. merge ---+# --- 7. 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.@@ -158,8 +178,14 @@ 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 maxspeed transit_lines admin_country admin_region admin_city"+echo "  new  : safety maxspeed transit_lines ma_pois admin_country admin_region admin_city" echo ""+if [[ "$SKIP_POIS" == "0" ]]; then+    echo "POI side files (emitted beside $OUT for the app to mmap):"+    echo "  $OUTDIR/poi_names.bin   (deduped NUL-terminated UTF-8 name table)"+    echo "  $OUTDIR/poi_index.bin   (flat 14-byte records: lat_e7,lon_e7,name_off,type)"+    echo ""+fi  if [[ "$PUBLISH" == "1" ]]; then     PUB_ARGS=("$OUT")
scripts/maps/poi_extract.cpp
diff --git a/scripts/maps/poi_extract.cpp b/scripts/maps/poi_extract.cppnew file mode 100644index 0000000000..7cabad1538--- /dev/null+++ b/scripts/maps/poi_extract.cpp@@ -0,0 +1,432 @@+// poi_extract.cpp — extract OSM POIs into the `ma_pois` tile layer + two side files.+//+// This is the P27 generator for the maps app's OWN POI layer. POI placement,+// name and type come from OpenStreetMap (baked at build time) so the app never+// scrapes a Google viewport; Google is hit only for rich details on tap.+//+// One pass over an OSM extract (nodes + way/relation centroids) produces three+// mutually-consistent outputs — same POI set, same coordinates:+//+//   1. <geojson>        newline-delimited GeoJSON (geojsonseq) Point features,+//                       fed to tippecanoe to build the `ma_pois` source-layer.+//                       Properties: name (string), type (number), osm_id (number).+//   2. poi_names.bin    DEDUPED UTF-8 name table: each unique name stored ONCE,+//                       NUL-terminated, concatenated. A "name start index" is the+//                       byte offset of the name's first byte. (Same convention as+//                       generator.cpp's road_names.bin.)+//   3. poi_index.bin    Flat array of fixed-size 14-byte records, little-endian,+//                       each a TRIPLE (coordinate, name_start_index, type):+//                           int32_t  lat_e7     latitude  * 1e7+//                           int32_t  lon_e7     longitude * 1e7+//                           uint32_t name_off   byte offset into poi_names.bin+//                           uint16_t type       POI type number (see below)+//                       Records are sorted ascending by the 64-bit Z-order+//                       (Morton) key of (lat,lon) — identical to generator.cpp's+//                       latlng_to_spatial — so the app can mmap + binary-scan a+//                       spatial range. POIs sharing a name point at the same+//                       name_off (that is the dedup win).+//+// A POI is any node OR way/relation-area that has BOTH a `name` tag AND one of+// the recognised POI keys (amenity/shop/tourism/leisure/office/healthcare). The+// value maps to a stable type number; a recognised key with an unmapped value+// falls into the 255 = "other" bucket. Way/relation geometry is reduced to a+// representative centroid (average of outer-ring node locations; nodes use their+// own location) — POIs render as points.+//+// ================================ TYPE MAP ================================+// Stable POI type-number enum (KEEP IN SYNC with the app + README). Never+// renumber an existing value — only append. 255 is the catch-all "other".+//+//   0  restaurant        14 place_of_worship   28 car+//   1  cafe              15 attraction         29 bakery+//   2  fast_food         16 parking            30 books+//   3  bar               17 cinema             31 furniture+//   4  shop (generic)    18 theatre            32 sports_shop+//   5  grocery           19 library            33 department_store+//   6  gas_station       20 post_office        34 dentist+//   7  pharmacy          21 police             35 doctor+//   8  hotel             22 fire_station       36 veterinary+//   9  bank              23 townhall           37 charging_station+//   10 hospital          24 clothing          38 museum+//   11 school            25 electronics       39 office (generic)+//   12 park              26 hardware          40 tourism_info+//   13 gym               27 beauty            41 florist+//   42 jewelry   43 optician   44 laundry   45 pet   46 liquor   47 toys+//   48 gift     49 marketplace+//   255 other+//+// Build:  g++ -O3 -std=c++17 poi_extract.cpp -o poi_extract -lz -lexpat -lbz2 -pthread+// Usage:  ./poi_extract IN.osm.pbf --geojson pois.geojsonseq \+//                        --names poi_names.bin --index poi_index.bin++#include <algorithm>+#include <cmath>+#include <cstdint>+#include <cstdio>+#include <cstring>+#include <fstream>+#include <iostream>+#include <string>+#include <unordered_map>+#include <vector>++#include <osmium/area/assembler.hpp>+#include <osmium/area/multipolygon_manager.hpp>+#include <osmium/handler.hpp>+#include <osmium/handler/node_locations_for_ways.hpp>+#include <osmium/index/map/flex_mem.hpp>+#include <osmium/io/any_input.hpp>+#include <osmium/osm/area.hpp>+#include <osmium/osm/node.hpp>+#include <osmium/relations/relations_manager.hpp>+#include <osmium/visitor.hpp>++using namespace std;++using index_type =+    osmium::index::map::FlexMem<osmium::unsigned_object_id_type, osmium::Location>;+using location_handler_type = osmium::handler::NodeLocationsForWays<index_type>;++static const uint16_t TYPE_OTHER = 255;++// ---- OSM tag -> type-number tables (see TYPE MAP above) ------------------+// Precedence when several keys are present: amenity, shop, tourism, leisure,+// office, healthcare. Unmapped-but-recognised keys => TYPE_OTHER.++static const unordered_map<string, uint16_t>& amenity_map() {+    static const unordered_map<string, uint16_t> m = {+        {"restaurant", 0}, {"food_court", 0},+        {"cafe", 1}, {"ice_cream", 1},+        {"fast_food", 2},+        {"bar", 3}, {"pub", 3}, {"biergarten", 3}, {"nightclub", 3},+        {"fuel", 6},+        {"pharmacy", 7},+        {"bank", 9}, {"atm", 9}, {"bureau_de_change", 9},+        {"hospital", 10}, {"clinic", 10},+        {"school", 11}, {"college", 11}, {"university", 11},+        {"kindergarten", 11}, {"language_school", 11}, {"driving_school", 11},+        {"place_of_worship", 14},+        {"parking", 16}, {"parking_entrance", 16}, {"bicycle_parking", 16},+        {"cinema", 17},+        {"theatre", 18}, {"arts_centre", 18},+        {"library", 19},+        {"post_office", 20},+        {"police", 21},+        {"fire_station", 22},+        {"townhall", 23}, {"courthouse", 23},+        {"car_rental", 28}, {"car_wash", 28}, {"car_sharing", 28},+        {"dentist", 34},+        {"doctors", 35},+        {"veterinary", 36},+        {"charging_station", 37},+        {"marketplace", 49},+    };+    return m;+}++static const unordered_map<string, uint16_t>& shop_map() {+    static const unordered_map<string, uint16_t> m = {+        {"supermarket", 5}, {"convenience", 5}, {"greengrocer", 5}, {"grocery", 5},+        {"chemist", 7}, {"pharmacy", 7},+        {"clothes", 24}, {"shoes", 24}, {"boutique", 24}, {"fashion", 24}, {"tailor", 24},+        {"electronics", 25}, {"mobile_phone", 25}, {"computer", 25}, {"hifi", 25},+        {"hardware", 26}, {"doityourself", 26}, {"trade", 26}, {"paint", 26},+        {"hairdresser", 27}, {"beauty", 27},+        {"car", 28}, {"car_repair", 28}, {"car_parts", 28}, {"tyres", 28},+        {"bakery", 29},+        {"books", 30}, {"stationery", 30},+        {"furniture", 31}, {"interior_decoration", 31}, {"houseware", 31},+        {"sports", 32}, {"outdoor", 32}, {"bicycle", 32},+        {"department_store", 33}, {"mall", 33},+        {"florist", 41},+        {"jewelry", 42}, {"jewellery", 42},+        {"optician", 43},+        {"laundry", 44}, {"dry_cleaning", 44},+        {"pet", 45},+        {"alcohol", 46}, {"wine", 46}, {"beverages", 46},+        {"toys", 47},+        {"gift", 48},+    };+    return m;+}++static const unordered_map<string, uint16_t>& tourism_map() {+    static const unordered_map<string, uint16_t> m = {+        {"hotel", 8}, {"motel", 8}, {"hostel", 8}, {"guest_house", 8}, {"apartment", 8},+        {"attraction", 15}, {"theme_park", 15}, {"zoo", 15}, {"viewpoint", 15},+        {"artwork", 15}, {"gallery", 15}, {"aquarium", 15},+        {"museum", 38},+        {"information", 40},+    };+    return m;+}++static const unordered_map<string, uint16_t>& leisure_map() {+    static const unordered_map<string, uint16_t> m = {+        {"park", 12}, {"garden", 12}, {"nature_reserve", 12},+        {"fitness_centre", 13}, {"sports_centre", 13},+    };+    return m;+}++static const unordered_map<string, uint16_t>& healthcare_map() {+    static const unordered_map<string, uint16_t> m = {+        {"pharmacy", 7},+        {"hospital", 10}, {"clinic", 10},+        {"dentist", 34},+        {"doctor", 35}, {"centre", 35},+        {"veterinary", 36},+        {"optometrist", 43},+    };+    return m;+}++// Classify a tag set. Returns true and sets `out_type` when the object is a POI+// (has one of the recognised POI keys). `office=*` maps to the generic office+// type (39) unless a higher-precedence key already matched.+static bool classify(const osmium::TagList& tags, uint16_t& out_type) {+    struct KV { const char* key; const unordered_map<string, uint16_t>* map; };+    const KV order[] = {+        {"amenity", &amenity_map()},+        {"shop", &shop_map()},+        {"tourism", &tourism_map()},+        {"leisure", &leisure_map()},+        {"healthcare", &healthcare_map()},+    };+    bool recognised = false;+    for (const auto& kv : order) {+        const char* v = tags.get_value_by_key(kv.key);+        if (!v || !*v || strcmp(v, "no") == 0) continue;+        recognised = true;+        auto it = kv.map->find(v);+        if (it != kv.map->end()) { out_type = it->second; return true; }+    }+    // office=* is a POI but almost always the generic office bucket.+    const char* off = tags.get_value_by_key("office");+    if (off && *off && strcmp(off, "no") != 0) {+        if (strcmp(off, "government") == 0) { out_type = 23; return true; }+        out_type = 39;+        return true;+    }+    if (recognised) { out_type = TYPE_OTHER; return true; }+    return false;+}++// ---- Morton / spatial key (identical to generator.cpp latlng_to_spatial) ---+static uint64_t latlng_to_spatial(double lat, double lon) {+    double x = (lon + 180.0) / 360.0;+    double y = (lat + 90.0) / 180.0;+    uint32_t ix = (uint32_t)(x * 4294967295.0);+    uint32_t iy = (uint32_t)(y * 4294967295.0);+    uint64_t res = 0;+    for (int i = 0; i < 32; i++) {+        res |= ((uint64_t)((ix >> i) & 1) << (2 * i));+        res |= ((uint64_t)((iy >> i) & 1) << (2 * i + 1));+    }+    return res;+}++struct Poi {+    double lat, lon;+    int32_t lat_e7, lon_e7;+    uint64_t morton;+    uint16_t type;+    int64_t osm_id;+    string name;+};++#pragma pack(push, 1)+struct PoiRecord {   // 14 bytes, little-endian+    int32_t lat_e7;+    int32_t lon_e7;+    uint32_t name_off;+    uint16_t type;+};+#pragma pack(pop)+static_assert(sizeof(PoiRecord) == 14, "PoiRecord must be 14 bytes");++class PoiHandler : public osmium::handler::Handler {+public:+    vector<Poi>& pois;+    explicit PoiHandler(vector<Poi>& out) : pois(out) {}++    void node(const osmium::Node& node) {+        const char* name = node.tags().get_value_by_key("name");+        if (!name || !*name) return;+        uint16_t type;+        if (!classify(node.tags(), type)) return;+        if (!node.location().valid()) return;+        add(node.location().lat(), node.location().lon(), type,+            (int64_t)node.id(), name);+    }++    void area(const osmium::Area& area) {+        const char* name = area.tags().get_value_by_key("name");+        if (!name || !*name) return;+        uint16_t type;+        if (!classify(area.tags(), type)) return;++        // Representative centroid: average of outer-ring node locations.+        double sum_lat = 0.0, sum_lon = 0.0;+        uint64_t n = 0;+        for (const auto& item : area) {+            if (item.type() != osmium::item_type::outer_ring) continue;+            const auto& ring = static_cast<const osmium::OuterRing&>(item);+            for (const auto& nr : ring) {+                if (!nr.location().valid()) continue;+                sum_lat += nr.location().lat();+                sum_lon += nr.location().lon();+                ++n;+            }+        }+        if (n == 0) return;+        // orig_id() is the source way/relation id; sign it negative for+        // relations so way/relation ids never collide in the osm_id attribute.+        int64_t oid = (int64_t)area.orig_id();+        if (!area.from_way()) oid = -oid;+        add(sum_lat / (double)n, sum_lon / (double)n, type, oid, name);+    }++private:+    void add(double lat, double lon, uint16_t type, int64_t osm_id,+             const char* name) {+        Poi p;+        p.lat = lat;+        p.lon = lon;+        p.lat_e7 = (int32_t)llround(lat * 1e7);+        p.lon_e7 = (int32_t)llround(lon * 1e7);+        p.morton = latlng_to_spatial(lat, lon);+        p.type = type;+        p.osm_id = osm_id;+        p.name = name;+        pois.push_back(std::move(p));+    }+};++static void json_escape(const string& s, string& out) {+    for (unsigned char c : s) {+        switch (c) {+            case '"': out += "\\\""; break;+            case '\\': out += "\\\\"; break;+            case '\n': out += "\\n"; break;+            case '\r': out += "\\r"; break;+            case '\t': out += "\\t"; break;+            default:+                if (c < 0x20) {+                    char buf[8];+                    snprintf(buf, sizeof(buf), "\\u%04x", c);+                    out += buf;+                } else {+                    out += (char)c;  // pass UTF-8 bytes through verbatim+                }+        }+    }+}++int main(int argc, char* argv[]) {+    if (argc < 2) {+        cerr << "Usage: " << argv[0]+             << " IN.osm.pbf --geojson FILE --names FILE --index FILE\n";+        return 1;+    }+    string in_path = argv[1];+    string geojson_path, names_path, index_path;+    for (int i = 2; i < argc; ++i) {+        string a = argv[i];+        if (a == "--geojson" && i + 1 < argc) geojson_path = argv[++i];+        else if (a == "--names" && i + 1 < argc) names_path = argv[++i];+        else if (a == "--index" && i + 1 < argc) index_path = argv[++i];+        else { cerr << "Unknown/incomplete arg: " << a << "\n"; return 1; }+    }+    if (geojson_path.empty() || names_path.empty() || index_path.empty()) {+        cerr << "ERROR: --geojson, --names and --index are all required\n";+        return 1;+    }++    vector<Poi> pois;++    osmium::io::File input_file{in_path};++    // Pass 1: collect multipolygon/boundary relations for the area assembler.+    osmium::area::Assembler::config_type assembler_config;+    assembler_config.create_empty_areas = false;+    osmium::area::MultipolygonManager<osmium::area::Assembler> mp_manager{+        assembler_config};+    cerr << "[poi] pass 1: reading relations\n";+    osmium::relations::read_relations(input_file, mp_manager);++    // Pass 2: nodes (direct) + assembled areas (closed ways + relations).+    index_type index;+    location_handler_type location_handler{index};+    location_handler.ignore_errors();+    PoiHandler handler{pois};++    cerr << "[poi] pass 2: extracting POIs\n";+    osmium::io::Reader reader{input_file};+    osmium::apply(reader, location_handler, handler,+                  mp_manager.handler([&handler](osmium::memory::Buffer&& buffer) {+                      osmium::apply(buffer, handler);+                  }));+    reader.close();++    cerr << "[poi] extracted " << pois.size() << " POI(s)\n";++    // Deterministic order: sort by Morton spatial key (ties broken by osm_id) so+    // both poi_index.bin and the geojson are stable across runs.+    sort(pois.begin(), pois.end(), [](const Poi& a, const Poi& b) {+        if (a.morton != b.morton) return a.morton < b.morton;+        return a.osm_id < b.osm_id;+    });++    // Build the deduped name pool (NUL-terminated) and the flat record array.+    ofstream names_out(names_path, ios::binary);+    ofstream index_out(index_path, ios::binary);+    ofstream geojson_out(geojson_path, ios::binary);+    if (!names_out || !index_out || !geojson_out) {+        cerr << "ERROR: cannot open output file(s)\n";+        return 1;+    }++    unordered_map<string, uint32_t> name_pool;+    uint32_t name_offset = 0;+    string line;++    for (const auto& p : pois) {+        auto it = name_pool.find(p.name);+        uint32_t off;+        if (it != name_pool.end()) {+            off = it->second;+        } else {+            off = name_offset;+            name_pool.emplace(p.name, off);+            names_out.write(p.name.c_str(), (streamsize)p.name.size());+            char nul = '\0';+            names_out.write(&nul, 1);+            name_offset += (uint32_t)p.name.size() + 1;+        }++        PoiRecord rec{p.lat_e7, p.lon_e7, off, p.type};+        index_out.write((const char*)&rec, sizeof(rec));++        line.clear();+        line += "{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[";+        char coord[64];+        snprintf(coord, sizeof(coord), "%.7f,%.7f", p.lon, p.lat);+        line += coord;+        line += "]},\"properties\":{\"name\":\"";+        json_escape(p.name, line);+        char props[64];+        snprintf(props, sizeof(props), "\",\"type\":%u,\"osm_id\":%lld}}\n",+                 (unsigned)p.type, (long long)p.osm_id);+        line += props;+        geojson_out.write(line.data(), (streamsize)line.size());+    }++    cerr << "[poi] wrote " << name_pool.size() << " unique name(s), "+         << pois.size() << " record(s)\n";+    cerr << "[poi]   " << geojson_path << " (geojsonseq for ma_pois)\n";+    cerr << "[poi]   " << names_path << " (" << name_offset << " bytes)\n";+    cerr << "[poi]   " << index_path << " ("+         << (uint64_t)pois.size() * sizeof(PoiRecord) << " bytes)\n";+    return 0;+}
scripts/maps/run_generator.sh
diff --git a/scripts/maps/run_generator.sh b/scripts/maps/run_generator.shindex f3ecc57fa7..8ce1848e84 100755--- a/scripts/maps/run_generator.sh+++ b/scripts/maps/run_generator.sh@@ -88,6 +88,11 @@ echo "[6/6] Uploading files to Cloudflare R2..." # directory. The offline TILE packs (zone_*.pmtiles) and the P11 transit index # (zone_*.transit) are published separately (extract_pmtiles.sh / gtfs_ingest) # and are intentionally NOT part of this graph upload.+#+# poi_names.bin / poi_index.bin are the P27 POI side files emitted by+# build_v5_pmtiles.sh (build_pois_layer.sh) beside v5.pmtiles. Copy them into+# "$DATA_DIR" before this sync (or point --workdir/--out there) so the app can+# fetch them from the same data.vayunmathur.com host as the graph. echo "Syncing single global graph to R2..."  aws s3 sync "$DATA_DIR" "s3://$BUCKET_NAME/" \@@ -101,7 +106,9 @@ aws s3 sync "$DATA_DIR" "s3://$BUCKET_NAME/" \     --include "edges.bin" \     --include "transit_voyages.bin" \     --include "transit_attributes.bin" \-    --include "lanes.bin"+    --include "lanes.bin" \+    --include "poi_names.bin" \+    --include "poi_index.bin"  echo "---------------------------------------------------------" echo "Pipeline Finished Successfully."