maps: show OSM hours, phone, website and address from the POI sidecar
- Commit
4a53c107f5432d3fc6fcac713838364802ad14d3- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-23 21:55 UTC (3 months ago)
- Parents
f1756c8
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 d81da253b3..06ceff580c 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -94,6 +94,14 @@ class MainActivity : ComponentActivity() { Triple("https://data.vayunmathur.com/intermediate.bin", "intermediate.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)),+ // The POI attribute sidecar (opening hours / phone / website /+ // address). REQUIRED here like the other two, so it must be+ // hosted BEFORE this app version ships: InitialDownloadChecker+ // gates on every file being present, and an entry with nothing+ // behind it strands users on the download screen. PoiIndex+ // itself treats the file as optional, so a device that somehow+ // lacks it degrades to no attributes rather than breaking.+ Triple("https://data.vayunmathur.com/poi_attrs.bin", "poi_attrs.bin", getString(R.string.downloading_poi_data)), Triple("https://data.vayunmathur.com/world.transit", "world.transit", getString(R.string.downloading_transit_data)) )) { val perms = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.ktindex 117e254e1c..3069c7b9e5 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt@@ -1,5 +1,6 @@ package com.vayunmathur.maps.data +import com.vayunmathur.maps.util.PoiIndex import com.vayunmathur.maps.util.Wikidata import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable@@ -32,11 +33,39 @@ sealed interface SpecificFeature { override val position: Position): RoutableFeature @Serializable data class GenericPlace(override val name: String, val phone: String?, val website: String?, val openingHours: OpeningHours?,- override val position: Position, val poiType: Int? = null): RoutableFeature+ override val position: Position, val poiType: Int? = null,+ /** Street address from the OSM `addr:*` tags, when we have them. */+ val address: String? = null): RoutableFeature @Serializable data class Route(val waypoints: List<RoutableFeature?>) : SpecificFeature } +/**+ * A place built from a coordinate, with whatever `poi_attrs.bin` knows about it.+ *+ * Every path that turns a name and a coordinate into a sheet goes through here, so+ * an offline search result opens the same populated sheet a tapped pin does — which+ * it did not before: search built these with every field null, so an offline result+ * showed a title and nothing else.+ *+ * Returns a bare place when the sidecar is absent or the point is not one of ours,+ * which is the same thing every caller used to produce unconditionally.+ */+fun osmPlace(name: String, position: Position, poiType: Int? = null): SpecificFeature.GenericPlace {+ val attrs = PoiIndex.attributesNear(position.latitude, position.longitude, name)+ return SpecificFeature.GenericPlace(+ name = name,+ phone = attrs?.phone,+ website = attrs?.website,+ // A string we could not parse would render as a confident week of "Closed",+ // so it is dropped in favour of whatever Google has.+ openingHours = attrs?.openingHours?.let(OpeningHours::from)?.takeIf { it.hasRules },+ position = position,+ poiType = poiType,+ address = attrs?.address,+ )+}+ typealias Feature1 = Feature<Geometry, JsonObject?> fun JsonObject.string(key: String): String? = this[key]?.jsonPrimitive?.content
maps/src/main/java/com/vayunmathur/maps/ui/GooglePoiLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/GooglePoiLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/GooglePoiLayer.ktindex 075e37e5d2..64908a2245 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/GooglePoiLayer.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/GooglePoiLayer.kt@@ -13,6 +13,7 @@ import androidx.compose.ui.unit.dp import com.vayunmathur.maps.data.Feature1 import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.data.google.GooglePoiPin+import com.vayunmathur.maps.data.osmPlace import com.vayunmathur.maps.data.string import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive@@ -130,7 +131,7 @@ fun Feature1.toSelectedGooglePoi(): SpecificFeature? { val name = props.string("name")?.ifBlank { null } ?: return null val lat = props["lat"]?.jsonPrimitive?.doubleOrNull ?: return null val lng = props["lng"]?.jsonPrimitive?.doubleOrNull ?: return null- return SpecificFeature.GenericPlace(name, null, null, null, Position(lng, lat))+ return osmPlace(name, Position(lng, lat)) } /** Category → pin colour, mirroring Vela's `PoiIcons.colorFor(group)` grouping. */
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.ktindex 015200d94a..790d4fe6b2 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MaPoisLayer.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MaPoisLayer.kt@@ -17,6 +17,7 @@ import androidx.compose.ui.unit.LayoutDirection import com.vayunmathur.library.ui.MapsPoiVectors import com.vayunmathur.maps.data.Feature1 import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.data.osmPlace import com.vayunmathur.maps.data.string import com.vayunmathur.maps.util.MapTileCache import com.vayunmathur.maps.util.PoiCategories@@ -46,25 +47,25 @@ const val MA_POIS_LAYER_ID = "ma-pois-icons" /** * 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+ * `ma_pois` source-layer baked into the overlay PMTiles archive 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+ /** Baked into the overlay PMTiles — read from the shared overlay URL. */+ val PMTILES_URL: String get() = MapTileCache.OVERLAY_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]), from z12 up. Reads the SAME shared- * [VectorSource] the admin/transit overlays use (single source — a second source- * on the same PMTiles triggers a directory parse error). The disc icons are- * runtime Canvas bitmaps (no sprite/glyph assets needed), so this renders even- * while the style's remote glyphs 404; the POI NAME is shown in the sheet on tap.+ * the numeric `type`, see [PoiCategories]), from z12 up. Takes the shared overlay+ * [VectorSource] the admin/transit overlays also read, since they are all layers+ * of the same archive. The disc icons are runtime Canvas bitmaps (no sprite/glyph+ * assets needed), so this renders even while the style's remote glyphs 404; the+ * POI NAME is shown in the sheet on tap. * * When [filterTypes] is non-null and non-empty the layer is filtered to just * those numeric types (the browse category chips, see MapPage); null shows all.@@ -128,13 +129,16 @@ fun MaPoisLayer(source: VectorSource, filterTypes: Set<Int>? = null) { * 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.+ *+ * [osmPlace] folds in the sidecar's hours / phone / website / address, so the sheet+ * has something to show before (and without) any Google response. */ 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 val type = props.string("type")?.toIntOrNull()- return SpecificFeature.GenericPlace(name, null, null, null, Position(pos.longitude, pos.latitude), poiType = type)+ return osmPlace(name, Position(pos.longitude, pos.latitude), poiType = type) } /** Build one category disc bitmap per POI type: a white-ringed colour disc with
maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.ktindex dee98ed478..80e9ce731c 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt@@ -3,6 +3,7 @@ import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.util.DateNameStyle import com.vayunmathur.library.util.localizedDayOfWeekNames import kotlinx.datetime.isoDayNumber+import android.content.ClipData import android.content.Context import android.content.Intent import androidx.compose.foundation.clickable@@ -23,6 +24,7 @@ import com.vayunmathur.library.ui.IconCall import com.vayunmathur.library.ui.IconDirections import com.vayunmathur.library.ui.IconDirectionsWalk import com.vayunmathur.library.ui.IconGlobe+import com.vayunmathur.library.ui.IconLocationOn import com.vayunmathur.library.ui.IconMenuBook import com.vayunmathur.library.ui.IconSave import com.vayunmathur.library.ui.IconSchedule@@ -41,12 +43,15 @@ import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.platform.ClipEntry+import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.AnnotatedString@@ -68,6 +73,7 @@ import com.vayunmathur.maps.ui.streetview.StreetViewScreen import com.vayunmathur.maps.data.timeFormat import com.vayunmathur.maps.util.SavedPlacesViewModel import com.vayunmathur.maps.util.SelectedFeatureViewModel+import kotlinx.coroutines.launch import kotlinx.datetime.TimeZone import kotlinx.datetime.format import kotlinx.datetime.toLocalDateTime@@ -116,7 +122,8 @@ fun PlaceSheet( ) = PlaceSheetContent( viewModel, savedPlacesViewModel, inactiveNavigation, feature, phone = feature.phone, website = feature.website, menu = null,- openingHours = feature.openingHours, onDepartures = onDepartures,+ openingHours = feature.openingHours, address = feature.address,+ onDepartures = onDepartures, requestDirections = requestDirections, ) @@ -130,6 +137,7 @@ private fun PlaceSheetContent( website: String?, menu: String?, openingHours: OpeningHours?,+ address: String? = null, onDepartures: (() -> Unit)? = null, requestDirections: () -> Unit, ) {@@ -138,12 +146,25 @@ private fun PlaceSheetContent( // If this is a restaurant/food place, ask fooddelivery whether it's orderable // (off the main thread, null-safe). Absent/not-orderable → null → no Order button. val orderDeepLink by rememberOrderDeepLink(context, feature, poi?.category)++ // Google wins on hours when it has them, and OSM fills in otherwise — including+ // offline, where the fetch simply returns nothing (there is no connectivity+ // check anywhere in this module, and none is needed: a failed request is+ // indistinguishable from "no data", which is exactly the behaviour wanted).+ val googleHours = poi?.hours.orEmpty()+ val osmHours = openingHours?.takeIf { googleHours.isEmpty() } Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {- PlaceHeader(feature.name, poi, hasOsmHours = openingHours != null)+ // The OSM block carries its own open/closed line, so the header only shows+ // Google's status when that block is absent — otherwise the sheet says the+ // same thing twice, in two different voices.+ PlaceHeader(feature.name, poi, showStatus = osmHours == null) PlaceActionRow( feature = feature,- phone = phone,- website = website,+ // OSM first, Google as the fallback. These used to be handed the OSM+ // values only, which were always null — so Call and Website were dead+ // buttons even when the enrichment had both.+ phone = phone ?: poi?.phone,+ website = website ?: poi?.website, inactiveNavigation = inactiveNavigation, savedPlacesViewModel = savedPlacesViewModel, requestDirections = requestDirections,@@ -157,12 +178,31 @@ private fun PlaceSheetContent( menu?.let { RestaurantItem({ IconMenuBook() }, stringResource(R.string.menu_label)) { goto(context, it) } }- openingHours?.let { OsmHours(it) }+ address?.let { AddressRow(it) }+ osmHours?.let { OsmHours(it) } StreetViewEntry(feature) // Reuse the existing enrichment sections (editorial / photos / popular // times / reviews). The header already shows category · price, so the // enrichment's own subtitle is suppressed to avoid duplication.- poi?.let { GooglePoiEnrichment(it, hasOsmHours = openingHours != null, showSubtitle = false) }+ poi?.let { GooglePoiEnrichment(it, showHours = osmHours == null, showSubtitle = false) }+ }+}++/**+ * The `addr:*` tags as one tappable row.+ *+ * New surface: nothing displayed an address before, because nothing had one —+ * `GoogleSearchResult.address` only ever appeared as a search-row subtitle. Tapping+ * copies it, which is what an address on a sheet is usually for.+ */+@Composable+private fun AddressRow(address: String) {+ val clipboard = LocalClipboard.current+ val scope = rememberCoroutineScope()+ RestaurantItem({ IconLocationOn() }, address) {+ scope.launch {+ clipboard.setClipEntry(ClipEntry(ClipData.newPlainText("address", address)))+ } } } @@ -195,7 +235,7 @@ private fun StreetViewEntry(feature: SpecificFeature.RoutableFeature) { } @Composable-private fun PlaceHeader(name: String, poi: GooglePoiInfo?, hasOsmHours: Boolean, modifier: Modifier = Modifier) {+private fun PlaceHeader(name: String, poi: GooglePoiInfo?, showStatus: Boolean, modifier: Modifier = Modifier) { Column(modifier, verticalArrangement = Arrangement.spacedBy(4.dp)) { Text(name, style = MaterialTheme.typography.titleLarge) @@ -216,10 +256,11 @@ private fun PlaceHeader(name: String, poi: GooglePoiInfo?, hasOsmHours: Boolean, } } - // Open-now status. When OSM opening hours are present the expandable- // hours block below shows this instead, so only surface Google's status- // string when we have nothing better.- if (!hasOsmHours) {+ // Open-now status, from Google when it has one. When the OSM hours block is+ // shown instead it carries its own status line, computed from a parsed+ // schedule rather than by string-matching English prose — so the caller+ // suppresses this to avoid saying it twice.+ if (showStatus) { poi?.statusText?.ifBlank { null }?.let { status -> val color = when (poi.openNow) { true -> MaterialTheme.colorScheme.tertiary
maps/src/main/java/com/vayunmathur/maps/ui/PoiEnrichment.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/PoiEnrichment.kt b/maps/src/main/java/com/vayunmathur/maps/ui/PoiEnrichment.ktindex 82e1448932..f592c4fbbc 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/PoiEnrichment.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/PoiEnrichment.kt@@ -64,7 +64,7 @@ import kotlin.time.Clock * reviews section) so the full set is reachable without stretching the sheet. */ @Composable-fun GooglePoiEnrichment(info: GooglePoiInfo, hasOsmHours: Boolean, showSubtitle: Boolean = true) {+fun GooglePoiEnrichment(info: GooglePoiInfo, showHours: Boolean, showSubtitle: Boolean = true) { if (info.isEmpty) return Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { // Price · category subtitle (rating itself is shown by the caller's header).@@ -81,10 +81,10 @@ fun GooglePoiEnrichment(info: GooglePoiInfo, hasOsmHours: Boolean, showSubtitle: Text(it, style = MaterialTheme.typography.bodyMedium, fontStyle = FontStyle.Italic, maxLines = 3) } - // Google's weekly hours — only when OSM didn't already provide them, to- // avoid showing the same schedule twice. Collapsed to TODAY's line by+ // Google's weekly hours, which win when it has them (the OSM block is+ // suppressed by the caller in that case). Collapsed to TODAY's line by // default (tap to expand all 7 days) so the sheet stays short.- if (!hasOsmHours && info.hours.isNotEmpty()) {+ if (showHours && info.hours.isNotEmpty()) { var showAllHours by remember { mutableStateOf(false) } val todayName = Clock.System.now() .toLocalDateTime(TimeZone.currentSystemDefault())
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 beefe4b720..7826ebdc11 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt@@ -5,6 +5,7 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.maps.data.RecentSearchStore import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.data.osmPlace import com.vayunmathur.maps.data.google.GoogleSearchDataSource import com.vayunmathur.maps.data.google.GoogleSearchResult import kotlinx.coroutines.Dispatchers@@ -196,11 +197,8 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati val hit = GoogleSearchDataSource.search(address, nearLat, nearLon).firstOrNull() onResolved( hit?.let {- SpecificFeature.GenericPlace(+ osmPlace( name = it.name.ifBlank { it.address ?: address },- phone = null,- website = null,- openingHours = null, position = Position(it.lng, it.lat), ) }@@ -229,15 +227,13 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati * through the same selection path as a tapped map pin, so * `SelectedFeatureViewModel.currentPoiInfo` then fetches the Google * enrichment for the sheet.+ *+ * The sidecar lookup matters most here: an offline result has no Google+ * enrichment coming, so without it the sheet opens with a title and nothing+ * else. */ fun toFeature(result: SearchResult): SpecificFeature.GenericPlace =- SpecificFeature.GenericPlace(- name = result.title,- phone = null,- website = null,- openingHours = null,- position = Position(result.lon, result.lat),- )+ osmPlace(name = result.title, position = Position(result.lon, result.lat)) /** * Reverse-geocode [lat],[lon] to the nearest addressable place and hand it@@ -250,11 +246,8 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati val hit = GoogleSearchDataSource.reverseGeocode(lat, lon) onResult( hit?.let {- SpecificFeature.GenericPlace(+ osmPlace( name = it.name.ifBlank { it.address ?: "" },- phone = null,- website = null,- openingHours = null, position = Position(it.lng, it.lat), ) }
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.ktindex 7d0d5ae9ea..f00f4f088d 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt@@ -20,16 +20,23 @@ import java.nio.channels.FileChannel * `{ 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).+ * * `poi_attrs.bin` — OPTIONAL attribute sidecar (opening hours, phone,+ * website, address, cuisine, wheelchair), indexed by the ORDINAL of the+ * matching `poi_index.bin` record. See `scripts/maps/osm_ingest/src/poi_attrs.rs`+ * for the layout. * * 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.+ * from the same host as the graph); queries then return empty lists. The sidecar+ * is separately optional: an install that has the index but not the attributes+ * keeps working, and every attribute reads as null. */ object PoiIndex { private const val TAG = "PoiIndex" const val INDEX_FILE = "poi_index.bin" const val NAMES_FILE = "poi_names.bin"+ const val ATTRS_FILE = "poi_attrs.bin" /** Bytes per record: int32 lat_e7 + int32 lon_e7 + uint32 name_off + uint16 type. */ private const val RECORD_BYTES = 14@@ -38,17 +45,77 @@ object PoiIndex { * blow up memory on a broad substring match. */ private const val CANDIDATE_CAP = 2_000 + // --- poi_attrs.bin layout (see poi_attrs.rs) ---------------------------+ private val ATTRS_MAGIC =+ byteArrayOf('M'.code.toByte(), 'A'.code.toByte(), 'P'.code.toByte(), 'A'.code.toByte())+ private const val ATTRS_VERSION = 1+ private const val ATTRS_HEADER_BYTES = 12+ /** `attr_off` for a POI that carries no attributes. */+ private const val NO_ATTRS = -1++ private const val KEY_OPENING_HOURS = 1+ private const val KEY_PHONE = 2+ private const val KEY_WEBSITE = 3+ private const val KEY_HOUSENUMBER = 4+ private const val KEY_STREET = 5+ private const val KEY_CITY = 6+ private const val KEY_POSTCODE = 7+ private const val KEY_CUISINE = 8+ private const val KEY_WHEELCHAIR = 9+ /** A single POI resolved from the index. */ data class PoiRecord( val latE7: Int, val lonE7: Int, val type: Int, val name: String,+ /**+ * Position in `poi_index.bin`, which is also this POI's key into the+ * attribute sidecar. -1 for a record not read from the index.+ */+ val ordinal: Int = -1, ) { val lat: Double get() = latE7 / 1e7 val lon: Double get() = lonE7 / 1e7 } + /**+ * The OSM tags a place sheet wants, for one POI. Every field is null when OSM+ * did not tag it — which is the common case for most of them.+ */+ data class PoiAttributes(+ val openingHours: String? = null,+ val phone: String? = null,+ val website: String? = null,+ val houseNumber: String? = null,+ val street: String? = null,+ val city: String? = null,+ val postcode: String? = null,+ val cuisine: String? = null,+ val wheelchair: String? = null,+ ) {+ /**+ * The `addr:*` tags as one display line, or null when there are none.+ *+ * House number joins the street with a space and the rest with commas, so a+ * partial address (very common in OSM — a street with no city) still reads+ * as an address rather than as a fragment.+ */+ val address: String?+ get() {+ val line = listOfNotNull(houseNumber, street)+ .joinToString(" ")+ .ifEmpty { null }+ return listOfNotNull(line, city, postcode)+ .joinToString(", ")+ .ifEmpty { null }+ }++ val isEmpty: Boolean+ get() = openingHours == null && phone == null && website == null &&+ address == null && cuisine == null && wheelchair == null+ }+ private var index: MappedByteBuffer? = null private var names: MappedByteBuffer? = null private var namesLen: Int = 0@@ -56,9 +123,17 @@ object PoiIndex { private var loaded = false private var tried = false + /** The attribute sidecar, or null when it is absent or does not match. */+ private var attrs: MappedByteBuffer? = null+ /** Byte offset of the blob, i.e. just past the offset array. */+ private var attrsBlobStart: Int = 0+ /** True once both side files were mapped successfully. */ val available: Boolean get() = loaded + /** True when the optional attribute sidecar is mapped and usable. */+ val attributesAvailable: Boolean get() = attrs != null+ /** Number of POI records available offline (0 when not loaded). */ val recordCount: Int get() = count @@ -88,6 +163,9 @@ object PoiIndex { count = (indexFile.length() / RECORD_BYTES).toInt() loaded = true Log.d(TAG, "Loaded $count POI records, names=${namesLen}B")+ // Separate and optional: a failure here leaves the index perfectly+ // usable, just without attributes.+ openAttrs(File(dir, ATTRS_FILE)) true } catch (e: Exception) { Log.w(TAG, "Failed to map POI side files", e)@@ -103,9 +181,61 @@ object PoiIndex { tried = false index = null names = null+ attrs = null return initialize(context) } + /**+ * Map the attribute sidecar, leaving [attrs] null if anything is off.+ *+ * The record-count check is the one that matters: the sidecar joins to the+ * index purely by position, so a sidecar from a different build would hand+ * every place someone else's phone number. Refusing the file is the only safe+ * response, and there is no way to detect the mismatch later.+ */+ private fun openAttrs(file: File) {+ attrs = null+ if (!file.isFile) {+ Log.d(TAG, "POI attribute sidecar absent")+ return+ }+ try {+ val buf = mapReadOnly(file).also { it.order(ByteOrder.LITTLE_ENDIAN) }+ if (buf.capacity() < ATTRS_HEADER_BYTES) {+ Log.w(TAG, "$ATTRS_FILE is truncated")+ return+ }+ for (i in ATTRS_MAGIC.indices) {+ if (buf.get(i) != ATTRS_MAGIC[i]) {+ Log.w(TAG, "$ATTRS_FILE has the wrong magic")+ return+ }+ }+ // Not a gate: the length prefixes let this reader step over a key added+ // by a later version, so a newer file is readable. A version it has+ // never heard of is worth a line in the log all the same.+ val version = buf.get(4).toInt()+ if (version != ATTRS_VERSION) {+ Log.d(TAG, "$ATTRS_FILE is version $version, expected $ATTRS_VERSION")+ }+ val attrCount = buf.getInt(8)+ if (attrCount != count) {+ Log.w(TAG, "$ATTRS_FILE has $attrCount slots but the index has $count; ignoring it")+ return+ }+ val blobStart = ATTRS_HEADER_BYTES + 4 * attrCount+ if (blobStart > buf.capacity()) {+ Log.w(TAG, "$ATTRS_FILE offset array runs past the file")+ return+ }+ attrsBlobStart = blobStart+ attrs = buf+ Log.d(TAG, "Loaded POI attributes for $attrCount record(s)")+ } catch (e: Exception) {+ Log.w(TAG, "Failed to map $ATTRS_FILE", e)+ }+ }+ private fun mapReadOnly(file: File): MappedByteBuffer = RandomAccessFile(file, "r").use { raf -> raf.channel.use { ch ->@@ -186,7 +316,7 @@ object PoiIndex { val lonE7 = recLonE7(i) out.add( Ranked(- PoiRecord(latE7, lonE7, recType(i), name),+ PoiRecord(latE7, lonE7, recType(i), name, i), rank, distanceSq(latE7 / 1e7, lonE7 / 1e7, nearLat, nearLon), )@@ -236,6 +366,7 @@ object PoiIndex { recLonE7(h.idx), recType(h.idx), nameAt(recNameOff(h.idx)) ?: "",+ h.idx, ) } }@@ -266,7 +397,7 @@ object PoiIndex { val latE7 = recLatE7(i) val lonE7 = recLonE7(i) if (latE7 in minLatE7..maxLatE7 && lonE7 in minLonE7..maxLonE7) {- out.add(PoiRecord(latE7, lonE7, recType(i), nameAt(recNameOff(i)) ?: ""))+ out.add(PoiRecord(latE7, lonE7, recType(i), nameAt(recNameOff(i)) ?: "", i)) } i++ }@@ -276,6 +407,126 @@ object PoiIndex { private class Ranked(val record: PoiRecord, val rank: Int, val distSq: Double) private class Hit(val idx: Int, val distSq: Double) + /**+ * The attributes of the [ordinal]th index record, or null when there are none.+ *+ * Two indexed reads and a short decode, no scan. Deliberately NOT called while+ * building viewport or search result lists, where it would decode hundreds of+ * records nobody looks at.+ *+ * Every offset is treated as untrusted. The file arrives over the network and a+ * truncated download must read as "no attributes", not throw out of a tap.+ */+ @Synchronized+ fun attributesAt(ordinal: Int): PoiAttributes? {+ val buf = attrs ?: return null+ if (ordinal < 0 || ordinal >= count) return null+ val off = buf.getInt(ATTRS_HEADER_BYTES + 4 * ordinal)+ if (off == NO_ATTRS || off < 0) return null+ // Bounded before the add, not after: `attrsBlobStart + off` can wrap negative+ // for a large positive off, and a negative index passes an `at + 2 > capacity`+ // test on its way to an IndexOutOfBoundsException.+ val blobLen = buf.capacity() - attrsBlobStart+ if (off > blobLen - 2) return null+ val at = attrsBlobStart + off+ val bodyLen = buf.getShort(at).toInt() and 0xFFFF+ val body = at + 2+ if (bodyLen > buf.capacity() - body) return null+ return decodeAttributes(buf, body, body + bodyLen)+ }++ /**+ * The attributes of the POI named [name] nearest to ([lat],[lon]), or null.+ *+ * This is the join a tapped tile feature needs, and the reason it is not an+ * exact coordinate match: the `ma_pois` tile layer quantises every point to its+ * tile's 4096-step grid (about 0.15 m at z16), so a tap's coordinate is close to+ * the side file's `lat_e7`/`lon_e7` but never equal to it.+ *+ * The name is matched too, not just the distance. A mall and a cafe inside it+ * can share a coordinate to within a metre, and attaching one's phone number to+ * the other is the kind of wrong that looks right.+ *+ * Costs one [nearest] call, which is a linear scan of the whole record array —+ * the same cost model [inViewport] documents and runs per viewport idle. If that+ * ever stops being affordable it is a limitation of all three, not of this one.+ */+ @Synchronized+ fun attributesNear(+ lat: Double,+ lon: Double,+ name: String,+ maxMeters: Double = 25.0,+ ): PoiAttributes? {+ if (attrs == null || name.isBlank()) return null+ val match = nearest(lat, lon, limit = 8, maxMeters = maxMeters)+ .firstOrNull { it.name == name }+ ?: return null+ return attributesAt(match.ordinal)+ }++ /**+ * Walk one record's `u8 key, u16 len, value` fields.+ *+ * A key this build does not know is stepped over using its length rather than+ * abandoning the record, which is the whole reason the values are+ * length-prefixed: a device on an older build must still read the keys it does+ * understand out of a newer file.+ */+ private fun decodeAttributes(buf: MappedByteBuffer, from: Int, to: Int): PoiAttributes? {+ var openingHours: String? = null+ var phone: String? = null+ var website: String? = null+ var houseNumber: String? = null+ var street: String? = null+ var city: String? = null+ var postcode: String? = null+ var cuisine: String? = null+ var wheelchair: String? = null++ var i = from+ while (i + 3 <= to) {+ val key = buf.get(i).toInt() and 0xFF+ val len = buf.getShort(i + 1).toInt() and 0xFFFF+ val start = i + 3+ if (start + len > to) break+ // Only decode the bytes of a key we are going to keep.+ val value: String? = when (key) {+ KEY_OPENING_HOURS, KEY_PHONE, KEY_WEBSITE, KEY_HOUSENUMBER, KEY_STREET,+ KEY_CITY, KEY_POSTCODE, KEY_CUISINE, KEY_WHEELCHAIR ->+ stringAt(buf, start, len)+ else -> null+ }+ when (key) {+ KEY_OPENING_HOURS -> openingHours = value+ KEY_PHONE -> phone = value+ KEY_WEBSITE -> website = value+ KEY_HOUSENUMBER -> houseNumber = value+ KEY_STREET -> street = value+ KEY_CITY -> city = value+ KEY_POSTCODE -> postcode = value+ KEY_CUISINE -> cuisine = value+ KEY_WHEELCHAIR -> wheelchair = value+ }+ i = start + len+ }++ val decoded = PoiAttributes(+ openingHours, phone, website, houseNumber, street, city, postcode, cuisine, wheelchair,+ )+ return decoded.takeUnless { it.isEmpty }+ }++ private fun stringAt(buf: MappedByteBuffer, off: Int, len: Int): String? {+ if (len <= 0) return null+ val bytes = ByteArray(len)+ // Absolute reads via a duplicate, so the shared buffer's position is untouched.+ val dup = buf.duplicate()+ dup.position(off)+ dup.get(bytes, 0, len)+ return String(bytes, Charsets.UTF_8)+ }+ /** 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))