networklocation: add OSM geocoder generator + assets packaging (db gitignored)
- Commit
3ba398fd4a1154021122efe79680d4525f2065d4- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-09 20:59 UTC (3 months ago)
- Parents
d4931a7
Diff
networklocation/build.gradle.kts
diff --git a/networklocation/build.gradle.kts b/networklocation/build.gradle.ktsindex b81f9f9c2d..ce0e13f46d 100644--- a/networklocation/build.gradle.kts+++ b/networklocation/build.gradle.kts@@ -10,9 +10,23 @@ android { defaultConfig { applicationId = "com.vayunmathur.networklocation" }+ androidResources {+ // The geocoder DB must stay uncompressed in the APK so it can be mmap'd directly from+ // the asset file descriptor (no unzip, no copy to filesDir).+ noCompress += "geodb"+ }+}++// The geocoder generator runs on the JVM test classpath (GeoDb* are pure-Kotlin). The planet+// build needs a large heap; override with GEOCODER_HEAP (e.g. 100g). Normal unit tests are+// unaffected — they won't allocate near this ceiling.+tasks.withType<Test>().configureEach {+ maxHeapSize = System.getenv("GEOCODER_HEAP") ?: "2g" } dependencies { // Geocoder DB is a self-contained mmap'd binary (see geocoder/). Block compression uses // java.util.zip (Deflate) — no external dependency needed for the core.+ // kotlinx-serialization-json (from the app convention) is used only by the generator to+ // parse osmium's GeoJSONSeq export. }
networklocation/src/main/assets/.gitignore
diff --git a/networklocation/src/main/assets/.gitignore b/networklocation/src/main/assets/.gitignorenew file mode 100644index 0000000000..0aed251b84--- /dev/null+++ b/networklocation/src/main/assets/.gitignore@@ -0,0 +1,4 @@+# The packed geocoder database is large (~1–1.5 GB) and is NOT committed. Generate it locally+# with tools/extract-osm-addresses.sh + the GeocoderGenerator, then upload to+# data.vayunmathur.com/geocoder/ ; release builds fetch it back into assets at build time.+*.geodb
networklocation/src/test/java/com/vayunmathur/networklocation/geocoder/GeocoderGenerator.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/geocoder/GeocoderGenerator.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/geocoder/GeocoderGenerator.ktnew file mode 100644index 0000000000..8e835ce281--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/geocoder/GeocoderGenerator.kt@@ -0,0 +1,114 @@+package com.vayunmathur.networklocation.geocoder++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.doubleOrNull+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import java.io.File+import kotlin.test.Test++/**+ * Real geocoder-DB generator. Not a unit test — it reuses the JVM test classpath (GeoDb* are+ * pure Kotlin) so it can be run without an Android device or a bespoke JavaExec setup.+ *+ * Pipeline (see tools/extract-osm-addresses.sh):+ * planet.osm.pbf --osmium--> addr.geojsonseq (one GeoJSON Feature per line, addr:* tags)+ * addr.geojsonseq --this--> geocoder.geodb (packed, mmap'd by the app at runtime)+ *+ * Run (give it a big heap for the whole planet):+ * GEOCODER_HEAP=100g ./gradlew :networklocation:testDebugUnitTest \+ * --tests '*GeocoderGenerator' \+ * -Dgeocoder.input=/data/addr.geojsonseq \+ * -Dgeocoder.output=networklocation/src/main/assets/geocoder.geodb+ *+ * With no -Dgeocoder.input it is a no-op, so ordinary test runs skip it.+ */+class GeocoderGenerator {++ @Test+ fun generate() {+ val input = System.getProperty("geocoder.input") ?: run {+ println("GeocoderGenerator: no -Dgeocoder.input set; skipping.")+ return+ }+ val output = System.getProperty("geocoder.output")+ ?: "networklocation/src/main/assets/geocoder.geodb"++ val inFile = File(input)+ require(inFile.exists()) { "input not found: $input" }+ val outFile = File(output).apply { parentFile?.mkdirs() }++ val json = Json { ignoreUnknownKeys = true; isLenient = true }+ val addresses = ArrayList<GeoAddress>(1 shl 20)+ var lines = 0L+ var skipped = 0L++ inFile.bufferedReader().useLines { seq ->+ for (raw in seq) {+ val line = raw.trim().trim('\u001e') // GeoJSONSeq may use RS (0x1e) separators+ if (line.isEmpty() || line[0] != '{') continue+ lines+++ val a = parseFeature(json, line)+ if (a == null) skipped++ else addresses.add(a)+ if (lines % 5_000_000L == 0L) {+ println("…parsed $lines features, kept ${addresses.size}")+ }+ }+ }++ println("Parsed $lines features; kept ${addresses.size}; skipped $skipped (no coord/street).")+ GeoDbWriter().write(outFile, addresses)+ val mb = outFile.length() / (1024.0 * 1024.0)+ println("Wrote ${outFile.absolutePath} — %.1f MB for ${addresses.size} addresses.".format(mb))+ }++ private fun parseFeature(json: Json, line: String): GeoAddress? {+ val obj = runCatching { json.parseToJsonElement(line).jsonObject }.getOrNull() ?: return null+ val props = obj["properties"]?.jsonObject ?: return null+ val street = props.str("addr:street")+ val house = props.str("addr:housenumber")+ // Require at least a street or house number to be a useful address.+ if (street.isEmpty() && house.isEmpty()) return null++ val geom = obj["geometry"]?.jsonObject ?: return null+ val coords = geom["coordinates"]?.jsonArray ?: return null+ val (lon, lat) = averageCoord(coords) ?: return null++ return GeoAddress(+ lat = lat,+ lon = lon,+ house = house,+ street = street,+ city = props.str("addr:city"),+ state = props.str("addr:state").ifEmpty { props.str("addr:province") },+ country = props.str("addr:country"),+ postcode = props.str("addr:postcode"),+ )+ }++ private fun JsonObject.str(key: String): String =+ (this[key] as? JsonPrimitive)?.content ?: ""++ /** Average of all [lon,lat] leaves — a cheap representative point for ways/areas. */+ private fun averageCoord(arr: JsonArray): Pair<Double, Double>? {+ var sumLon = 0.0+ var sumLat = 0.0+ var n = 0+ fun walk(e: JsonArray) {+ // A coordinate pair is [number, number]; otherwise recurse into nested arrays.+ val first = e.firstOrNull()+ if (first is JsonPrimitive && first.doubleOrNull != null) {+ val lon = (e[0] as JsonPrimitive).doubleOrNull ?: return+ val lat = (e[1] as JsonPrimitive).doubleOrNull ?: return+ sumLon += lon; sumLat += lat; n+++ } else {+ for (child in e) if (child is JsonArray) walk(child)+ }+ }+ walk(arr)+ return if (n == 0) null else (sumLon / n) to (sumLat / n)+ }+}
networklocation/tools/extract-osm-addresses.sh
diff --git a/networklocation/tools/extract-osm-addresses.sh b/networklocation/tools/extract-osm-addresses.shnew file mode 100644index 0000000000..9799b447b0--- /dev/null+++ b/networklocation/tools/extract-osm-addresses.sh@@ -0,0 +1,36 @@+#!/usr/bin/env bash+#+# Extract every addressed object from an OSM planet (or region) extract into a GeoJSONSeq file+# that GeocoderGenerator packs into geocoder.geodb.+#+# ./extract-osm-addresses.sh /path/planet.osm.pbf /path/addr.geojsonseq+#+# Needs `osmium` (osmium-tool). On the planet this takes a while and ~a few GB of scratch.+# Try a country/region extract first to validate the pipeline before the full planet.+set -euo pipefail++IN="${1:?usage: extract-osm-addresses.sh <planet.osm.pbf> <out.geojsonseq>}"+OUT="${2:?usage: extract-osm-addresses.sh <planet.osm.pbf> <out.geojsonseq>}"+TMP="$(mktemp -d)"+trap 'rm -rf "$TMP"' EXIT++echo "==> Filtering objects that carry addr:housenumber (nodes, ways, relations)…"+# Keep any object with a house number OR a street; -R keeps referenced nodes so way/area+# geometries can be assembled for centroids.+osmium tags-filter "$IN" \+ n/addr:housenumber w/addr:housenumber r/addr:housenumber \+ n/addr:street w/addr:street r/addr:street \+ -o "$TMP/addr.osm.pbf"++echo "==> Exporting to GeoJSONSeq (one Feature per line)…"+# --add-unique-id gives stable ids; areas/ways are exported with their geometry and the+# generator averages coordinates to a representative point.+osmium export "$TMP/addr.osm.pbf" \+ -f geojsonseq \+ --geometry-types=point,linestring,polygon \+ -o "$OUT" \+ --overwrite++echo "==> Done: $OUT ($(du -h "$OUT" | cut -f1))"+echo "Next: GEOCODER_HEAP=100g ./gradlew :networklocation:testDebugUnitTest --tests '*GeocoderGenerator' \\"+echo " -Dgeocoder.input=$OUT -Dgeocoder.output=networklocation/src/main/assets/geocoder.geodb"