maps(P27-APP): OSM ma_pois render + tap->Google details, retire Google viewport scrape, offline POI index reader + search
- Commit
727949e4b2ebf5c5fd7405e65088333ea71113b2- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-18 04:34 UTC (3 months ago)
- Parents
afe1987
- MyMapLayers: draw baked ma_pois source-layer (v5 pmtiles) as category icons (data-driven by numeric type) + name label at z12+, replacing the ambient GooglePoiLayer. - MapPage: retire the Google viewport scrape (drop onViewport snapshotFlow); tap ma_pois -> select GenericPlace(name,coord) so currentPoiInfo fetches Google rich details. - MaPoisLayer: MA_POIS_LAYER_ID, MaPoisLayer(source), Feature1.toSelectedMaPoi(), per-type disc icons. - PoiIndex: mmap reader for poi_index.bin (14B LE records) + poi_names.bin (NUL-terminated pool); name prefix/substring search + nearest bbox lookup, loaded from getExternalFilesDir. - PoiCategories: shared type->label/color/glyph map (README type map). - MapsSearchViewModel: resolve POI-name queries offline first, Google stays fallback/for addresses. - MainActivity: download poi_index.bin + poi_names.bin. - strings: downloading_poi_data.
Diff
maps/src/main/java/com/vayunmathur/maps/MainActivity.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt b/maps/src/main/java/com/vayunmathur/maps/MainActivity.ktindex bb3de31c6e..8188b6e6b1 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -89,7 +89,9 @@ class MainActivity : ComponentActivity() { Triple("https://data.vayunmathur.com/edges.bin", "edges.bin", getString(R.string.downloading_road_data)), Triple("https://data.vayunmathur.com/transit_voyages.bin", "transit_voyages.bin", getString(R.string.downloading_road_data)), Triple("https://data.vayunmathur.com/transit_attributes.bin", "transit_attributes.bin", getString(R.string.downloading_road_data)),- Triple("https://data.vayunmathur.com/lanes.bin", "lanes.bin", getString(R.string.downloading_road_data))+ Triple("https://data.vayunmathur.com/lanes.bin", "lanes.bin", getString(R.string.downloading_road_data)),+ Triple("https://data.vayunmathur.com/poi_index.bin", "poi_index.bin", getString(R.string.downloading_poi_data)),+ Triple("https://data.vayunmathur.com/poi_names.bin", "poi_names.bin", getString(R.string.downloading_poi_data)) )) { val perms = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // POST_NOTIFICATIONS is runtime-grantable on API 33+
maps/src/main/java/com/vayunmathur/maps/ui/MaPoisLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MaPoisLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MaPoisLayer.ktnew file mode 100644index 0000000000..551b80fa46--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MaPoisLayer.kt@@ -0,0 +1,137 @@+package com.vayunmathur.maps.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.unit.dp+import com.vayunmathur.maps.data.Feature1+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.data.string+import com.vayunmathur.maps.util.MapTileCache+import com.vayunmathur.maps.util.PoiCategories+import org.maplibre.compose.expressions.dsl.case+import org.maplibre.compose.expressions.dsl.const+import org.maplibre.compose.expressions.dsl.feature+import org.maplibre.compose.expressions.dsl.image+import org.maplibre.compose.expressions.dsl.interpolate+import org.maplibre.compose.expressions.dsl.linear+import org.maplibre.compose.expressions.dsl.switch+import org.maplibre.compose.expressions.dsl.zoom+import org.maplibre.compose.expressions.value.IntValue+import org.maplibre.compose.expressions.value.StringValue+import org.maplibre.compose.expressions.value.SymbolAnchor+import org.maplibre.compose.layers.SymbolLayer+import org.maplibre.compose.sources.VectorSource+import org.maplibre.compose.util.MaplibreComposable+import org.maplibre.spatialk.geojson.Point+import org.maplibre.spatialk.geojson.Position++/** Symbol layer id for the OSM POI icons — hit-tested in MapPage.onMapClick so a+ * POI tap selects the place (name/coord) and fetches Google rich details. */+const val MA_POIS_LAYER_ID = "ma-pois-icons"+private const val MA_POIS_LABEL_LAYER_ID = "ma-pois-labels"++/**+ * OUR baked OSM POI layer (P27). Placement / name / type come from the+ * `ma_pois` source-layer baked into the v5 basemap PMTiles by the generator+ * (z12–z16), replacing the runtime Google viewport scrape for ambient pins —+ * Google is now hit only for rich details when a POI is tapped+ * (see [Feature1.toSelectedMaPoi] + SelectedFeatureViewModel.currentPoiInfo).+ */+object MaPoisSource {+ /** Baked into the v5 basemap PMTiles — read from the shared base URL. */+ val PMTILES_URL: String get() = MapTileCache.BASEMAP_PMTILES_URL+ const val SOURCE_LAYER: String = "ma_pois"+ val available: Boolean get() = PMTILES_URL.isNotBlank()+}++/**+ * Draw the `ma_pois` source-layer: a category icon per feature (data-driven off+ * the numeric `type`, see [PoiCategories]) plus a name label, from z12 up. Reads+ * the same shared [VectorSource] the admin/transit overlays use. Harmless no-op+ * while the source-layer is absent (until v5 is regenerated with `ma_pois`).+ */+@Composable+@MaplibreComposable+fun MaPoisLayer(source: VectorSource) {+ val icons = remember { poiIcons() }++ // Category icon, chosen by the numeric `type` (0..49, 255 = other).+ SymbolLayer(+ MA_POIS_LAYER_ID,+ source,+ sourceLayer = MaPoisSource.SOURCE_LAYER,+ minZoom = 12f,+ iconImage = switch(+ feature["type"].cast<IntValue>(),+ *PoiCategories.ALL_TYPES+ .map { t -> case(t, image(icons.getValue(t))) }+ .toTypedArray(),+ fallback = image(icons.getValue(PoiCategories.TYPE_OTHER)),+ ),+ iconSize = interpolate(+ linear(), zoom(),+ 12 to const(0.35f),+ 15 to const(0.5f),+ 18 to const(0.7f),+ ),+ )++ // Name label under the icon.+ SymbolLayer(+ MA_POIS_LABEL_LAYER_ID,+ source,+ sourceLayer = MaPoisSource.SOURCE_LAYER,+ minZoom = 14f,+ textField = feature["name"].cast<StringValue>(),+ textColor = const(Color(0xFF37474F)),+ textHaloColor = const(Color.White),+ textHaloWidth = const(1.5.dp),+ textAnchor = const(SymbolAnchor.Top),+ )+}++/**+ * Convert a tapped `ma_pois` feature into a selectable place. Its name comes+ * from the feature properties and its coordinate from the point geometry; we+ * reuse [SpecificFeature.GenericPlace] (name + position) so the existing+ * `SelectedFeatureViewModel.currentPoiInfo` flow fetches the Google enrichment+ * and `GooglePoiEnrichment` renders in the sheet — no new detail path needed.+ */+fun Feature1.toSelectedMaPoi(): SpecificFeature? {+ val props = properties ?: return null+ val name = props.string("name")?.ifBlank { null } ?: return null+ val pos = (geometry as? Point)?.coordinates ?: return null+ return SpecificFeature.GenericPlace(name, null, null, null, Position(pos.longitude, pos.latitude))+}++/** Generate one category disc icon per POI type (Decision D5: Compose/Canvas+ * runtime bitmaps rather than sprite assets). */+private fun poiIcons(): Map<Int, ImageBitmap> =+ PoiCategories.ALL_TYPES.associateWith { t ->+ poiDisc(PoiCategories.colorHex(t), PoiCategories.glyph(t))+ }++/** A white-ringed colour disc with a centred white glyph. */+private fun poiDisc(colorHex: String, glyph: String): ImageBitmap {+ val size = 64+ val bmp = android.graphics.Bitmap.createBitmap(size, size, android.graphics.Bitmap.Config.ARGB_8888)+ val canvas = android.graphics.Canvas(bmp)+ val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG)+ val cx = size / 2f+ val cy = size / 2f+ paint.color = android.graphics.Color.WHITE+ canvas.drawCircle(cx, cy, size / 2f - 2f, paint)+ paint.color = runCatching { android.graphics.Color.parseColor(colorHex) }+ .getOrDefault(android.graphics.Color.parseColor("#5F6368"))+ canvas.drawCircle(cx, cy, size / 2f - 6f, paint)+ paint.color = android.graphics.Color.WHITE+ paint.textAlign = android.graphics.Paint.Align.CENTER+ paint.textSize = size * 0.46f+ paint.isFakeBoldText = true+ val fm = paint.fontMetrics+ canvas.drawText(glyph, cx, cy - (fm.ascent + fm.descent) / 2f, paint)+ return bmp.asImageBitmap()+}
maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.ktindex 0ee4b0f99c..c607bc7e3c 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -54,7 +54,6 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.retain.retain import androidx.compose.runtime.setValue-import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color@@ -147,8 +146,9 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, val selectedTransitStop by transitViewModel.selected.collectAsState() val departuresState by transitViewModel.departures.collectAsState() - // Google POI overlay pins (viewport scrape → custom layer, replacing the- // suppressed native basemap POIs).+ // Retired ambient Google POI pins (P27): the overlay no longer renders these+ // (MyMapLayers draws the baked `ma_pois` layer instead) and no viewport is+ // fed, so this stays empty. Kept for the positional MyMapLayers call. val googlePins by poiViewModel.pins.collectAsState() // Search-result pins (from the Google search page) drawn on the map.@@ -176,20 +176,11 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, } } - // P23: feed the Google POI overlay the live viewport as the camera MOVES- // (not only on idle) so the VM can refresh snappily when the centre jumps.- // The VM debounces, applies a min-interval and LRU-caches the keyless scrape,- // and prefetches a padded bbox, so streaming every camera change here can't- // hammer Google.- LaunchedEffect(Unit) {- snapshotFlow { camera.position }- .collect { pos ->- if (pos.zoom >= 11.0) {- val bbox = camera.projection?.queryVisibleBoundingBox() ?: return@collect- poiViewModel.onViewport(bbox.north, bbox.east, bbox.south, bbox.west)- }- }- }+ // P27: ambient POIs now come from OUR baked `ma_pois` layer (the v5 PMTiles+ // source-layer), so the Google viewport scrape that used to discover pins as+ // the camera moved is RETIRED — Google is hit only on tap for rich details.+ // The GooglePoiMapViewModel is left wired but never fed a viewport, so no+ // ambient scrape happens. // Online-tiles-only: the basemap always streams live (offline zone tile // packs were removed). Offline ROUTING still works via the downloaded graph.@@ -501,10 +492,11 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, } // Hit-test the search-result pins first, then the- // ambient Google POI overlay — a pin tap re-selects- // the place as a GenericPlace so+ // baked ma_pois layer — a POI tap selects the+ // place (name + coord) as a GenericPlace so // SelectedFeatureViewModel.currentPoiInfo fetches- // the enrichment and GooglePoiEnrichment renders.+ // the Google rich details and GooglePoiEnrichment+ // renders. val pinHit = projection?.queryRenderedFeatures( offset, setOf(SEARCH_RESULT_LAYER_ID)@@ -519,8 +511,8 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, )?.firstNotNullOfOrNull { it.toSelectedFamilyMember() } ?: projection?.queryRenderedFeatures( offset,- setOf(GOOGLE_POI_LAYER_ID)- )?.firstNotNullOfOrNull { it.toSelectedGooglePoi() }+ setOf(MA_POIS_LAYER_ID)+ )?.firstNotNullOfOrNull { it.toSelectedMaPoi() } if (pinHit != null) { if (selectedFeature is SpecificFeature.Route) viewModel.setInactiveNavigation( selectedFeature as SpecificFeature.Route
maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.ktindex 75687d9dea..cf011ae638 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt@@ -145,9 +145,12 @@ fun MyMapLayers( TransitLinesLayer(adminSource) } - // Custom Google POI overlay (replaces suppressed native basemap POIs).- // Rendered above traffic but below the user puck.- GooglePoiLayer(googlePins)+ // OUR baked OSM POI overlay (P27): placement/name/type come from the+ // `ma_pois` source-layer in the v5 basemap PMTiles, replacing the Google+ // viewport scrape for ambient pins. Google is hit only on tap for rich+ // details (see MapPage.onMapClick -> toSelectedMaPoi). Reuses the shared+ // vector source; harmless no-op until v5 ships the `ma_pois` layer.+ MaPoisLayer(adminSource) // Saved-place pins (Home / Work / starred list). Tap re-selects the // place → PlaceSheet (Vela's SavedPin).
maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.ktindex 9efc0ae288..76cf146600 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt@@ -7,6 +7,7 @@ import com.vayunmathur.maps.data.RecentSearchStore import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.data.google.GoogleSearchDataSource import com.vayunmathur.maps.data.google.GoogleSearchResult+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow@@ -15,6 +16,7 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext import org.maplibre.spatialk.geojson.Position /**@@ -41,6 +43,15 @@ private fun GoogleSearchResult.toSearchResult() = SearchResult( category = category, ) +private fun PoiIndex.PoiRecord.toSearchResult() = SearchResult(+ id = "poi:$latE7:$lonE7:${name.hashCode()}",+ title = name,+ subtitle = PoiCategories.label(type),+ lat = lat,+ lon = lon,+ category = PoiCategories.label(type),+)+ /** * Owns the text query and result list for the maps search page. *@@ -83,6 +94,18 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati } searchJob = viewModelScope.launch { delay(250)+ // Try the offline OSM POI index first (P27): resolving a POI name+ // locally avoids a Google call. Google stays the fallback (and+ // handles addresses, which the POI index doesn't carry).+ val app = getApplication<Application>()+ val offline = withContext(Dispatchers.IO) {+ PoiIndex.initialize(app)+ PoiIndex.searchByName(query, nearLat, nearLon, limit = 20)+ }+ if (offline.isNotEmpty()) {+ _results.value = offline.map { it.toSearchResult() }+ return@launch+ } // GoogleSearchDataSource.search does its own Dispatchers.IO + never // throws (empty list on any scrape/path failure). _results.value = GoogleSearchDataSource.search(query, nearLat, nearLon)
maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.ktnew file mode 100644index 0000000000..8372f2a7a0--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt@@ -0,0 +1,113 @@+package com.vayunmathur.maps.util++/**+ * Shared metadata for the OSM POI `type` enum baked into the v5 `ma_pois`+ * source-layer and the `poi_index.bin` side file (P27). The numbering is the+ * stable type map defined in `scripts/maps/README.md` / `poi_extract.cpp`+ * (0..49 categories, 255 = "other"); never renumber, only append.+ *+ * Kept in one place so the map render ([com.vayunmathur.maps.ui.MaPoisLayer],+ * icon colour + glyph) and the offline search ([PoiIndex], the result subtitle)+ * agree on how a numeric type maps to a colour / glyph / human label.+ */+object PoiCategories {+ /** Catch-all bucket for a recognised POI key with an unmapped value. */+ const val TYPE_OTHER: Int = 255++ /** Every type number the generator can emit, for building the icon switch. */+ val ALL_TYPES: List<Int> = (0..49).toList() + TYPE_OTHER++ /** Human-readable category label (used as the search-result subtitle). */+ fun label(type: Int): String = when (type) {+ 0 -> "Restaurant"+ 1 -> "Cafe"+ 2 -> "Fast food"+ 3 -> "Bar"+ 4 -> "Shop"+ 5 -> "Grocery"+ 6 -> "Gas station"+ 7 -> "Pharmacy"+ 8 -> "Hotel"+ 9 -> "Bank"+ 10 -> "Hospital"+ 11 -> "School"+ 12 -> "Park"+ 13 -> "Gym"+ 14 -> "Place of worship"+ 15 -> "Attraction"+ 16 -> "Parking"+ 17 -> "Cinema"+ 18 -> "Theatre"+ 19 -> "Library"+ 20 -> "Post office"+ 21 -> "Police"+ 22 -> "Fire station"+ 23 -> "Town hall"+ 24 -> "Clothing"+ 25 -> "Electronics"+ 26 -> "Hardware"+ 27 -> "Beauty"+ 28 -> "Car"+ 29 -> "Bakery"+ 30 -> "Books"+ 31 -> "Furniture"+ 32 -> "Sports"+ 33 -> "Department store"+ 34 -> "Dentist"+ 35 -> "Doctor"+ 36 -> "Veterinary"+ 37 -> "Charging station"+ 38 -> "Museum"+ 39 -> "Office"+ 40 -> "Tourist info"+ 41 -> "Florist"+ 42 -> "Jewelry"+ 43 -> "Optician"+ 44 -> "Laundry"+ 45 -> "Pet"+ 46 -> "Liquor"+ 47 -> "Toys"+ 48 -> "Gift"+ 49 -> "Marketplace"+ else -> "Place"+ }++ /**+ * Category pin colour (hex `#RRGGBB`, consumed by `Color.parseColor`).+ * Grouped so related categories read as a family (food = warm, health =+ * red, retail = blue, nature/green, civic = slate …).+ */+ fun colorHex(type: Int): String = when (type) {+ 0, 2, 29, 49 -> "#E8590C" // food: restaurant / fast food / bakery / marketplace+ 1 -> "#F9AB00" // cafe+ 3, 46 -> "#A142F4" // bar / liquor+ 5, 12, 37 -> "#34A853" // grocery / park / charging (green)+ 6 -> "#0F9D58" // gas station+ 7, 10, 34, 35, 36 -> "#D93025" // health: pharmacy / hospital / dentist / doctor / vet+ 8 -> "#4285F4" // hotel+ 9 -> "#188038" // bank+ 11, 19, 38 -> "#F29900" // education/culture: school / library / museum+ 13 -> "#7E57C2" // gym+ 14 -> "#8D6E63" // place of worship+ 15, 40 -> "#FF6D00" // attraction / tourist info+ 16, 20, 21, 22, 23, 39 -> "#5F6368" // civic/parking/office (slate)+ 17, 18 -> "#AB47BC" // cinema / theatre+ 24, 27, 41, 42, 47, 48 -> "#E91E63" // apparel/beauty/florist/jewelry/toys/gift+ 25, 43 -> "#1A73E8" // electronics / optician+ 26, 31, 30, 45 -> "#795548" // hardware / furniture / books / pet+ 28 -> "#455A64" // car+ else -> "#1A73E8" // generic shop / department / sports / laundry / other+ }++ /** Single-character glyph drawn in the pin (a hint, not unique per type). */+ fun glyph(type: Int): String = when (type) {+ 0 -> "R"; 1 -> "C"; 2 -> "F"; 3 -> "B"; 4 -> "S"; 5 -> "G"; 6 -> "\u26FD"+ 7 -> "+"; 8 -> "H"; 9 -> "$"; 10 -> "H"; 11 -> "S"; 12 -> "P"; 13 -> "G"+ 14 -> "W"; 15 -> "A"; 16 -> "P"; 17 -> "C"; 18 -> "T"; 19 -> "L"; 20 -> "P"+ 21 -> "P"; 22 -> "F"; 23 -> "T"; 24 -> "C"; 25 -> "E"; 26 -> "H"; 27 -> "B"+ 28 -> "C"; 29 -> "B"; 30 -> "B"; 31 -> "F"; 32 -> "S"; 33 -> "D"; 34 -> "D"+ 35 -> "M"; 36 -> "V"; 37 -> "E"; 38 -> "M"; 39 -> "O"; 40 -> "i"; 41 -> "F"+ 42 -> "J"; 43 -> "O"; 44 -> "L"; 45 -> "P"; 46 -> "L"; 47 -> "T"; 48 -> "G"+ 49 -> "M"; else -> "\u2022"+ }+}
maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.ktnew file mode 100644index 0000000000..05021bcfed--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt@@ -0,0 +1,253 @@+package com.vayunmathur.maps.util++import android.content.Context+import android.util.Log+import java.io.File+import java.io.RandomAccessFile+import java.nio.ByteOrder+import java.nio.MappedByteBuffer+import java.nio.channels.FileChannel++/**+ * Offline reader for the P27 POI side files, memory-mapped from the app's+ * external files dir (the same dir the routing graph downloads into, see+ * [OfflineRouter] / MainActivity's InitialDownloadChecker):+ *+ * * `poi_names.bin` — unique UTF-8 names, each NUL-terminated, concatenated in+ * first-seen order. A `name_off` is the byte offset of a name's first byte;+ * shared names resolve to the same offset.+ * * `poi_index.bin` — a flat array of 14-byte little-endian records+ * `{ int32 lat_e7; int32 lon_e7; uint32 name_off; uint16 type }`,+ * `count = filesize / 14`, sorted ascending by the 64-bit Morton(lat,lon)+ * key (the key itself is not stored).+ *+ * It exposes a name search (prefix/substring over the deduped name pool) and a+ * spatial nearest lookup, so a POI query can resolve locally without a Google+ * call. Everything is a harmless no-op until both files are present (they ship+ * from the same host as the graph); queries then return empty lists.+ */+object PoiIndex {+ private const val TAG = "PoiIndex"+ const val INDEX_FILE = "poi_index.bin"+ const val NAMES_FILE = "poi_names.bin"++ /** Bytes per record: int32 lat_e7 + int32 lon_e7 + uint32 name_off + uint16 type. */+ private const val RECORD_BYTES = 14++ /** Cap on candidates gathered before ranking, so a planet-sized pool can't+ * blow up memory on a broad substring match. */+ private const val CANDIDATE_CAP = 2_000++ /** A single POI resolved from the index. */+ data class PoiRecord(+ val latE7: Int,+ val lonE7: Int,+ val type: Int,+ val name: String,+ ) {+ val lat: Double get() = latE7 / 1e7+ val lon: Double get() = lonE7 / 1e7+ }++ private var index: MappedByteBuffer? = null+ private var names: MappedByteBuffer? = null+ private var namesLen: Int = 0+ private var count: Int = 0+ private var loaded = false+ private var tried = false++ /** True once both side files were mapped successfully. */+ val available: Boolean get() = loaded++ /** Number of POI records available offline (0 when not loaded). */+ val recordCount: Int get() = count++ /**+ * Map both side files from [Context.getExternalFilesDir]. Idempotent and+ * safe to call repeatedly; returns false (and stays a no-op) when either+ * file is missing. Not retried automatically after a failure unless+ * [reload] is called (e.g. after the download completes).+ */+ @Synchronized+ fun initialize(context: Context): Boolean {+ if (loaded) return true+ if (tried) return false+ tried = true+ val dir = context.getExternalFilesDir(null) ?: return false+ val indexFile = File(dir, INDEX_FILE)+ val namesFile = File(dir, NAMES_FILE)+ if (!indexFile.isFile || !namesFile.isFile) {+ Log.d(TAG, "POI side files absent (index=${indexFile.exists()} names=${namesFile.exists()})")+ return false+ }+ return try {+ index = mapReadOnly(indexFile).also { it.order(ByteOrder.LITTLE_ENDIAN) }+ val namesBuf = mapReadOnly(namesFile)+ names = namesBuf+ namesLen = namesBuf.capacity()+ count = (indexFile.length() / RECORD_BYTES).toInt()+ loaded = true+ Log.d(TAG, "Loaded $count POI records, names=${namesLen}B")+ true+ } catch (e: Exception) {+ Log.w(TAG, "Failed to map POI side files", e)+ index = null; names = null; loaded = false+ false+ }+ }++ /** Force a re-map after the side files finish downloading. */+ @Synchronized+ fun reload(context: Context): Boolean {+ loaded = false+ tried = false+ index = null+ names = null+ return initialize(context)+ }++ private fun mapReadOnly(file: File): MappedByteBuffer =+ RandomAccessFile(file, "r").use { raf ->+ raf.channel.use { ch ->+ // Demo side files fit in a single mapping; cap defensively at 2GB.+ val len = minOf(ch.size(), Int.MAX_VALUE.toLong())+ ch.map(FileChannel.MapMode.READ_ONLY, 0, len)+ }+ }++ /** Read the NUL-terminated UTF-8 name that starts at byte [off], or null. */+ private fun nameAt(off: Int): String? {+ val buf = names ?: return null+ if (off < 0 || off >= namesLen) return null+ var end = off+ while (end < namesLen && buf.get(end).toInt() != 0) end+++ val n = end - off+ if (n <= 0) return null+ val bytes = ByteArray(n)+ // Absolute bulk get keeps the shared buffer's position untouched.+ val dup = buf.duplicate()+ dup.position(off)+ dup.get(bytes, 0, n)+ return String(bytes, Charsets.UTF_8)+ }++ private fun recLatE7(i: Int): Int = index!!.getInt(i * RECORD_BYTES)+ private fun recLonE7(i: Int): Int = index!!.getInt(i * RECORD_BYTES + 4)+ private fun recNameOff(i: Int): Int = index!!.getInt(i * RECORD_BYTES + 8)+ private fun recType(i: Int): Int = index!!.getShort(i * RECORD_BYTES + 12).toInt() and 0xFFFF++ /**+ * Case-insensitive prefix/substring search over the deduped name pool,+ * returning matching POIs ranked prefix-first then by distance to+ * ([nearLat],[nearLon]). Returns an empty list when nothing matches or the+ * index isn't loaded.+ */+ @Synchronized+ fun searchByName(+ query: String,+ nearLat: Double,+ nearLon: Double,+ limit: Int = 20,+ ): List<PoiRecord> {+ if (!loaded) return emptyList()+ val q = query.trim().lowercase()+ if (q.isEmpty()) return emptyList()++ // Pass 1: walk the name pool once, recording matching offsets and their+ // rank (0 = prefix match, 1 = substring). Decoding each unique name once+ // is the dedup win the side-file layout is designed for.+ val buf = names ?: return emptyList()+ val matchRank = HashMap<Int, Int>()+ var pos = 0+ while (pos < namesLen) {+ var end = pos+ while (end < namesLen && buf.get(end).toInt() != 0) end+++ if (end > pos) {+ val name = nameAt(pos)+ if (name != null) {+ val lower = name.lowercase()+ if (lower.startsWith(q)) matchRank[pos] = 0+ else if (lower.contains(q)) matchRank[pos] = 1+ }+ }+ pos = end + 1+ }+ if (matchRank.isEmpty()) return emptyList()++ // Pass 2: scan records, keeping those whose name offset matched.+ val out = ArrayList<Ranked>(minOf(CANDIDATE_CAP, count))+ var i = 0+ while (i < count && out.size < CANDIDATE_CAP) {+ val off = recNameOff(i)+ val rank = matchRank[off]+ if (rank != null) {+ val name = nameAt(off) ?: ""+ val latE7 = recLatE7(i)+ val lonE7 = recLonE7(i)+ out.add(+ Ranked(+ PoiRecord(latE7, lonE7, recType(i), name),+ rank,+ distanceSq(latE7 / 1e7, lonE7 / 1e7, nearLat, nearLon),+ )+ )+ }+ i+++ }+ out.sortWith(compareBy({ it.rank }, { it.distSq }))+ return out.take(limit).map { it.record }+ }++ /**+ * Nearest POIs to ([lat],[lon]) within [maxMeters], closest first (bbox+ * pre-filter + squared-distance sort). Names are decoded only for the+ * returned winners. Empty when the index isn't loaded.+ */+ @Synchronized+ fun nearest(+ lat: Double,+ lon: Double,+ limit: Int = 20,+ maxMeters: Double = 250.0,+ ): List<PoiRecord> {+ if (!loaded) return emptyList()+ val dLat = maxMeters / 111_320.0+ val cosLat = Math.cos(Math.toRadians(lat)).coerceAtLeast(1e-6)+ val dLon = maxMeters / (111_320.0 * cosLat)+ val minLatE7 = ((lat - dLat) * 1e7).toInt()+ val maxLatE7 = ((lat + dLat) * 1e7).toInt()+ val minLonE7 = ((lon - dLon) * 1e7).toInt()+ val maxLonE7 = ((lon + dLon) * 1e7).toInt()++ val hits = ArrayList<Hit>()+ var i = 0+ while (i < count) {+ val latE7 = recLatE7(i)+ val lonE7 = recLonE7(i)+ if (latE7 in minLatE7..maxLatE7 && lonE7 in minLonE7..maxLonE7) {+ hits.add(Hit(i, distanceSq(latE7 / 1e7, lonE7 / 1e7, lat, lon)))+ }+ i+++ }+ hits.sortBy { it.distSq }+ return hits.take(limit).map { h ->+ PoiRecord(+ recLatE7(h.idx),+ recLonE7(h.idx),+ recType(h.idx),+ nameAt(recNameOff(h.idx)) ?: "",+ )+ }+ }++ private class Ranked(val record: PoiRecord, val rank: Int, val distSq: Double)+ private class Hit(val idx: Int, val distSq: Double)++ /** Cheap squared planar distance (deg², lon scaled by cos lat) for ranking. */+ private fun distanceSq(aLat: Double, aLon: Double, bLat: Double, bLon: Double): Double {+ val cosLat = Math.cos(Math.toRadians((aLat + bLat) / 2.0))+ val dLat = aLat - bLat+ val dLon = (aLon - bLon) * cosLat+ return dLat * dLat + dLon * dLon+ }+}
maps/src/main/res/values/strings.xml
diff --git a/maps/src/main/res/values/strings.xml b/maps/src/main/res/values/strings.xmlindex 8b2477651d..601edec4be 100644--- a/maps/src/main/res/values/strings.xml+++ b/maps/src/main/res/values/strings.xml@@ -137,6 +137,8 @@ <string name="downloading_navigation_metadata">Downloading Navigation Tiling Metadata…</string> <!-- MainActivity: Status text while road data downloads --> <string name="downloading_road_data">Downloading Road Data…</string>+ <!-- MainActivity: Status text while offline POI index downloads -->+ <string name="downloading_poi_data">Downloading Points of Interest…</string> <!-- MainActivity: Button to request location permission --> <string name="grant_location_permission">Grant Location Permission</string>