maps P3: Google search/geocode; remove amenities.db
- Commit
48c955655f3c9f4657c410f686b05650bd080fe7- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-16 22:28 UTC (3 months ago)
- Parents
0b5af5a
Diff
maps/build.gradle.kts
diff --git a/maps/build.gradle.kts b/maps/build.gradle.ktsindex 6794269d21..9eea87ad9c 100644--- a/maps/build.gradle.kts+++ b/maps/build.gradle.kts@@ -3,7 +3,6 @@ plugins { // Listing screenshots come from Compose previews (src/screenshotTest), not from an // instrumented test on a device. Same `:<module>:metadata` task name either way. id("common-conventions-preview-metadata")- alias(libs.plugins.ksp) } launcherIcon {@@ -38,8 +37,5 @@ dependencies { implementation(libs.flatgeobuf) -- // room- implementRoom(libs) implementation(project(":library:downloadservice")) }
maps/schemas/com.vayunmathur.maps.data.AmenityDatabase/1.json
diff --git a/maps/schemas/com.vayunmathur.maps.data.AmenityDatabase/1.json b/maps/schemas/com.vayunmathur.maps.data.AmenityDatabase/1.jsondeleted file mode 100644index 95d6ff45ac..0000000000--- a/maps/schemas/com.vayunmathur.maps.data.AmenityDatabase/1.json+++ /dev/null@@ -1,108 +0,0 @@-{- "formatVersion": 1,- "database": {- "version": 1,- "identityHash": "a5c7268631151b19565b65ba588c0bf3",- "entities": [- {- "tableName": "AmenityTag",- "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`nodeID` INTEGER NOT NULL, `key` TEXT NOT NULL, `value` TEXT NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)",- "fields": [- {- "fieldPath": "nodeID",- "columnName": "nodeID",- "affinity": "INTEGER",- "notNull": true- },- {- "fieldPath": "key",- "columnName": "key",- "affinity": "TEXT",- "notNull": true- },- {- "fieldPath": "value",- "columnName": "value",- "affinity": "TEXT",- "notNull": true- },- {- "fieldPath": "id",- "columnName": "id",- "affinity": "INTEGER",- "notNull": true- }- ],- "primaryKey": {- "autoGenerate": true,- "columnNames": [- "id"- ]- },- "indices": [- {- "name": "index_AmenityTag_nodeID",- "unique": false,- "columnNames": [- "nodeID"- ],- "orders": [],- "createSql": "CREATE INDEX IF NOT EXISTS `index_AmenityTag_nodeID` ON `${TABLE_NAME}` (`nodeID`)"- }- ]- },- {- "tableName": "AmenityEntity",- "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT NOT NULL, `lat` REAL NOT NULL, `lon` REAL NOT NULL, PRIMARY KEY(`id`))",- "fields": [- {- "fieldPath": "id",- "columnName": "id",- "affinity": "INTEGER",- "notNull": true- },- {- "fieldPath": "name",- "columnName": "name",- "affinity": "TEXT",- "notNull": true- },- {- "fieldPath": "lat",- "columnName": "lat",- "affinity": "REAL",- "notNull": true- },- {- "fieldPath": "lon",- "columnName": "lon",- "affinity": "REAL",- "notNull": true- }- ],- "primaryKey": {- "autoGenerate": false,- "columnNames": [- "id"- ]- },- "indices": [- {- "name": "idx_amenity_coords",- "unique": false,- "columnNames": [- "lat",- "lon"- ],- "orders": [],- "createSql": "CREATE INDEX IF NOT EXISTS `idx_amenity_coords` ON `${TABLE_NAME}` (`lat`, `lon`)"- }- ]- }- ],- "setupQueries": [- "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",- "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'a5c7268631151b19565b65ba588c0bf3')"- ]- }-}\ No newline at end of file
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 118f5ca883..01fd03bcd0 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -58,7 +58,6 @@ class MainActivity : ComponentActivity() { setContent { DynamicTheme { InitialDownloadChecker(ds, listOf(- Triple("https://data.vayunmathur.com/amenities.db", "amenities.db", getString(R.string.downloading_amenity_database)), Triple("https://data.vayunmathur.com/metadata.bin", "metadata.bin", getString(R.string.downloading_navigation_metadata)), Triple("https://data.vayunmathur.com/road_names.bin", "road_names.bin", getString(R.string.downloading_road_data)), Triple("https://data.vayunmathur.com/intermediate.bin", "intermediate.bin", getString(R.string.downloading_road_data)),@@ -113,7 +112,7 @@ fun Navigation( val backStack = rememberNavBackStack<Route>(Route.MapPage) MainNavigation(backStack) { entry<Route.MapPage> {- MapPage(backStack, viewModel, zonesViewModel, savedPlacesViewModel, poiViewModel)+ MapPage(backStack, viewModel, zonesViewModel, savedPlacesViewModel, poiViewModel, searchViewModel) } entry<Route.DownloadedMapsPage> { DownloadedMapsPage(backStack, zonesViewModel)
maps/src/main/java/com/vayunmathur/maps/data/AmenityRepository.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/AmenityRepository.kt b/maps/src/main/java/com/vayunmathur/maps/data/AmenityRepository.ktdeleted file mode 100644index 628b1794a1..0000000000--- a/maps/src/main/java/com/vayunmathur/maps/data/AmenityRepository.kt+++ /dev/null@@ -1,33 +0,0 @@-package com.vayunmathur.maps.data--import android.content.Context--/**- * Singleton owner of the [AmenityDatabase]. Uses the existing custom- * [buildAmenityDatabase] (external file + createFromFile, unencrypted) so- * the builder stays identical; we just ensure it is called once and the- * instance is shared process-wide instead of threaded through composables.- */-class AmenityRepository private constructor(private val db: AmenityDatabase) {-- fun tagDao(): TagDao = db.tagDao()- fun amenityDao(): AmenityDao = db.amenityDao()- fun addressDao(): AddressDao = db.addressDao()-- // Convenience wrappers used by ViewModels- suspend fun getTags(nodeId: Long): List<AmenityTag> = db.tagDao().getTags(nodeId)- suspend fun getInBBox(query: String, latMin: Double, lonMin: Double, latMax: Double, lonMax: Double): List<AmenityEntity> =- db.amenityDao().getInBBox(query, latMin, lonMin, latMax, lonMax)- suspend fun searchAddresses(query: String, limit: Int = 50): List<AddressResult> =- db.addressDao().search(query, limit)- fun getDatabase(): AmenityDatabase = db-- companion object {- @Volatile private var instance: AmenityRepository? = null-- fun get(context: Context): AmenityRepository =- instance ?: synchronized(this) {- instance ?: AmenityRepository(buildAmenityDatabase(context.applicationContext)).also { instance = it }- }- }-}
maps/src/main/java/com/vayunmathur/maps/data/RecentSearchStore.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/RecentSearchStore.kt b/maps/src/main/java/com/vayunmathur/maps/data/RecentSearchStore.ktnew file mode 100644index 0000000000..775b638314--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/data/RecentSearchStore.kt@@ -0,0 +1,57 @@+package com.vayunmathur.maps.data++import android.content.Context+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map+import kotlinx.serialization.json.Json++/**+ * Persists the user's most-recent search queries so the search page can offer+ * them before any text is typed (Vela's `RecentSearchStore` analog).+ *+ * Backed by a single JSON-encoded ordered string list in [DataStoreUtils] (a+ * plain preferences string, not the removed amenities.db): most-recent first,+ * de-duped case-insensitively, capped at [MAX] entries. Offline search is gone+ * (Decision D2), but the recents list is local and works without network.+ */+class RecentSearchStore private constructor(private val ds: DataStoreUtils) {++ /** Recent queries, most-recent first. Empty until the first search. */+ val recents: Flow<List<String>> = ds.stringFlow(KEY).map { decode(it) }++ /** Snapshot of the current recents (non-suspending; reads the mirrored state). */+ fun current(): List<String> = decode(ds.getString(KEY))++ /** Record [query], moving it to the front and dropping any duplicate. Blank+ * queries are ignored. */+ suspend fun add(query: String) {+ val q = query.trim()+ if (q.isEmpty()) return+ val updated = (listOf(q) + current().filter { !it.equals(q, ignoreCase = true) }).take(MAX)+ ds.setString(KEY, Json.encodeToString(updated))+ }++ /** Clear all recent searches. */+ suspend fun clear() {+ ds.setString(KEY, "")+ }++ private fun decode(raw: String?): List<String> =+ raw?.takeIf { it.isNotBlank() }+ ?.let { runCatching { Json.decodeFromString<List<String>>(it) }.getOrNull() }+ ?: emptyList()++ companion object {+ private const val KEY = "maps_recent_searches"+ private const val MAX = 10++ @Volatile private var instance: RecentSearchStore? = null++ fun get(context: Context): RecentSearchStore =+ instance ?: synchronized(this) {+ instance ?: RecentSearchStore(DataStoreUtils.getInstance(context.applicationContext))+ .also { instance = it }+ }+ }+}
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 5cce031163..f0c7e9596e 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt@@ -27,8 +27,6 @@ sealed interface SpecificFeature { data class GenericPlace(override val name: String, val phone: String?, val website: String?, val openingHours: OpeningHours?, override val position: Position): RoutableFeature @Serializable- data class TransitStop(override val name: String, val stopCode: String?, val gtfsFeed: String?, override val position: Position): RoutableFeature- @Serializable data class Route(val waypoints: List<RoutableFeature?>) : SpecificFeature }
maps/src/main/java/com/vayunmathur/maps/data/Tag.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/Tag.kt b/maps/src/main/java/com/vayunmathur/maps/data/Tag.ktdeleted file mode 100644index c9e03616ac..0000000000--- a/maps/src/main/java/com/vayunmathur/maps/data/Tag.kt+++ /dev/null@@ -1,125 +0,0 @@-package com.vayunmathur.maps.data--import android.content.Context-import androidx.room.ColumnInfo-import androidx.room.Dao-import androidx.room.Database-import androidx.room.Entity-import androidx.room.Index-import androidx.room.Insert-import androidx.room.PrimaryKey-import androidx.room.Query-import androidx.room.Room-import androidx.room.RoomDatabase-import androidx.room.SkipQueryVerification-import androidx.sqlite.db.SupportSQLiteDatabase-import java.io.File--@Entity-data class AmenityTag(- @ColumnInfo(index = true)- val nodeID: Long,- val key: String,- val value: String,- @PrimaryKey(autoGenerate = true) val id: Long = 0-)--@Dao-interface TagDao {- @Insert- suspend fun insert(tag: AmenityTag)- @Insert- suspend fun insertAll(tags: List<AmenityTag>)- @Query("SELECT * FROM AmenityTag WHERE nodeID = :nodeID")- suspend fun getTags(nodeID: Long): List<AmenityTag>-}--/**- * Represents the Amenities table using 64-bit Geohash integers- * instead of SpatiaLite geometries.- */-@Entity(indices = [Index(value = ["lat", "lon"], name = "idx_amenity_coords")])-data class AmenityEntity(- @PrimaryKey val id: Long,- val name: String,- val lat: Double,- val lon: Double-)--@Dao-interface AmenityDao {- // use fts5 search- @SkipQueryVerification- @Query("""- SELECT a.* FROM AmenityEntity a - JOIN Amenities_fts f ON a.id = f.rowid - WHERE f.name MATCH :query - AND a.lat BETWEEN :latMin AND :latMax - AND a.lon BETWEEN :lonMin AND :lonMax- """)- suspend fun getInBBox(query: String, latMin: Double, lonMin: Double, latMax: Double, lonMax: Double): List<AmenityEntity>-}--/**- * A fuzzy address-search hit. Not a Room @Entity: the `Addresses` /- * `Addresses_fts` tables are built server-side (like `Amenities_fts`) and live- * in the downloaded amenities.db, so they are queried with- * @SkipQueryVerification and mapped into this plain result class.- */-data class AddressResult(- val id: Long,- val address: String,- val lat: Double,- val lon: Double-)--@Dao-interface AddressDao {- /**- * Closest-match address search. [query] is an FTS5 expression built from the- * user's text (prefix tokens joined with OR); bm25() orders rows so the best- * matches come first.- */- @SkipQueryVerification- @Query("""- SELECT a.id AS id, a.address AS address, a.lat AS lat, a.lon AS lon- FROM Addresses a- JOIN Addresses_fts f ON a.id = f.rowid- WHERE Addresses_fts MATCH :query- ORDER BY bm25(Addresses_fts)- LIMIT :limit- """)- suspend fun search(query: String, limit: Int = 50): List<AddressResult>-}--@Database(entities = [AmenityTag::class, AmenityEntity::class], version = 1, exportSchema = false)-abstract class AmenityDatabase : RoomDatabase() {- abstract fun tagDao(): TagDao- abstract fun amenityDao(): AmenityDao- abstract fun addressDao(): AddressDao-}--fun buildAmenityDatabase(context: Context): AmenityDatabase {- val dbFile = File(context.getExternalFilesDir(null), "amenities.db")-- // Use `createFromFile` so Room opens the pre-downloaded SQLite file at- // its real on-disk path. Passing dbFile.absolutePath as the `name`- // argument (as the previous code did) makes Room interpret the slashes- // as subdirectory components under /data/data/<pkg>/databases/, which- // either fails to open or creates an unexpected file. The "name"- // argument is just a logical identifier in this mode.- return Room.databaseBuilder(- context,- AmenityDatabase::class.java,- "amenities.db"- )- .createFromFile(dbFile)- .setJournalMode(RoomDatabase.JournalMode.TRUNCATE) // External storage can be flaky with WAL- .addCallback(object : RoomDatabase.Callback() {- override fun onOpen(db: SupportSQLiteDatabase) {- super.onOpen(db)- db.execSQL("PRAGMA synchronous = NORMAL")- }- })- .build()-}\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/data/google/GoogleSearchDataSource.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/google/GoogleSearchDataSource.kt b/maps/src/main/java/com/vayunmathur/maps/data/google/GoogleSearchDataSource.ktnew file mode 100644index 0000000000..b9d00e4b35--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/data/google/GoogleSearchDataSource.kt@@ -0,0 +1,206 @@+package com.vayunmathur.maps.data.google++import com.vayunmathur.library.network.NetworkClient+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonNull+import java.net.URLEncoder++/**+ * One search / reverse-geocode hit. Unlike [GooglePoiInfo] (the bottom-sheet+ * enrichment, which carries no id/name/position because the caller already knew+ * the place), a search result must be self-describing: it drops a pin on the map+ * and, on tap, re-selects the place — so it carries a stable [id], [name],+ * position and a [category]/[address] for the row and pin styling.+ */+data class GoogleSearchResult(+ val id: String,+ val name: String,+ val lat: Double,+ val lng: Double,+ val category: String? = null,+ val address: String? = null,+)++/**+ * Keyless Google text search + reverse-geocode, replacing the removed+ * amenities.db FTS search and address geocoder (Decision D2: search is now+ * online-only, no offline fallback).+ *+ * This is the list-and-geocode sibling of [GooglePoiDataSource] (single-place+ * enrichment) and [GooglePoiDiscovery] (viewport ambient pins): it hits the same+ * undocumented keyless `search?tbm=map` endpoint a logged-out browser uses, and+ * parses the guard-prefixed positional JSON array via the shared [GoogleResponse]+ * helpers. Every path is fragile — a Google reshape makes fields go null rather+ * than throw, and keyless responses are bot-degraded. All network runs on+ * [Dispatchers.IO]; callers ([MapsSearchViewModel]) debounce the query (D7).+ *+ * NOTE (on-device): the live scrape needs a device with network — it can't be+ * exercised at compile time. See [GooglePoiDataSource] for the cookie-warming+ * device-verification caveat.+ */+object GoogleSearchDataSource {++ // Same calibrated endpoints/identity as GooglePoiDataSource (Vela, 2026-06).+ private const val SEARCH_ENDPOINT =+ "https://www.google.com/search?tbm=map&authuser=0&hl=en&gl=us"+ private const val SESSION_WARM_URL = "https://www.google.com/maps?hl=en&gl=us"+ private const val USER_AGENT =+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " ++ "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"+ private val REQUEST_HEADERS = mapOf(+ "User-Agent" to USER_AGENT,+ "Accept-Language" to "en-US,en;q=0.9",+ "Referer" to "https://www.google.com/maps/",+ )++ /** Cap the result list so a broad query ("coffee") doesn't return a huge+ * list — matches the ~20 rows a Vela search surfaces. */+ private const val MAX_RESULTS = 20++ @Volatile private var sessionWarmed = false++ /**+ * Free-text search for [query], biased toward [nearLat],[nearLon] (the map+ * centre). Never throws — returns an empty list when the scrape fails or the+ * positional paths drift. Runs on [Dispatchers.IO].+ */+ suspend fun search(query: String, nearLat: Double, nearLon: Double): List<GoogleSearchResult> {+ if (query.isBlank()) return emptyList()+ return runCatching { fetchSearch(query, nearLat, nearLon) }.getOrDefault(emptyList())+ }++ /**+ * Reverse-geocode a coordinate to the nearest addressable place (the+ * replacement for the removed address FTS geocoder). Returns null when there+ * is no confident match or the scrape fails. Runs on [Dispatchers.IO].+ */+ suspend fun reverseGeocode(lat: Double, lon: Double): GoogleSearchResult? =+ runCatching { fetchReverse(lat, lon) }.getOrNull()++ private suspend fun fetchSearch(query: String, lat: Double, lon: Double): List<GoogleSearchResult> =+ withContext(Dispatchers.IO) {+ warmSession()+ val pb = buildPb(query, lat, lon)+ val url = "$SEARCH_ENDPOINT&q=${query.enc()}&pb=${pb.enc()}"+ val body = get(url) ?: return@withContext emptyList()+ val root = GoogleResponse.parseOrNull(body) ?: return@withContext emptyList()+ parseResults(root)+ }++ private suspend fun fetchReverse(lat: Double, lon: Double): GoogleSearchResult? =+ withContext(Dispatchers.IO) {+ warmSession()+ // A "lat,lon" query geocodes the point; Google answers with either a+ // focused list or a single geocoded node.+ val query = "$lat,$lon"+ val pb = buildPb(query, lat, lon)+ val url = "$SEARCH_ENDPOINT&q=${query.enc()}&pb=${pb.enc()}"+ val body = get(url) ?: return@withContext null+ val root = GoogleResponse.parseOrNull(body) ?: return@withContext null+ parseResults(root).firstOrNull() ?: parseSingle(root)+ }++ /**+ * The list-returning parse: walk every entry at [Paths.RESULTS] and pull the+ * result fields. Entries missing a name or position are dropped; the rest are+ * de-duped by feature id and capped at [MAX_RESULTS].+ */+ private fun parseResults(root: JsonElement): List<GoogleSearchResult> {+ val list = root.at(*Paths.RESULTS).arr() ?: return emptyList()+ return list.mapNotNull { entry -> entryToResult(entry) }+ .distinctBy { it.id }+ .take(MAX_RESULTS)+ }++ /** A single geocoded node → wrap as [null, node] so the entry-relative paths+ * (place node at [1]) resolve unchanged, then map it. */+ private fun parseSingle(root: JsonElement): GoogleSearchResult? {+ val node = root.at(*Paths.SINGLE) ?: return null+ return entryToResult(JsonArray(listOf(JsonNull, node)))+ }++ private fun entryToResult(entry: JsonElement): GoogleSearchResult? {+ val name = entry.at(*Paths.NAME).str() ?: return null+ val plat = entry.at(*Paths.LAT).dbl() ?: return null+ val plng = entry.at(*Paths.LNG).dbl() ?: return null+ return GoogleSearchResult(+ id = entry.at(*Paths.FEATURE_ID).str() ?: "$plat,$plng",+ name = name,+ lat = plat,+ lng = plng,+ category = entry.at(*Paths.CATEGORY).str(),+ address = entry.at(*Paths.ADDRESS).str()+ ?: entry.at(*Paths.ADDRESS_LINES).arr()+ ?.mapNotNull { it.str() }?.joinToString(", ")?.ifBlank { null },+ )+ }++ // --- HTTP plumbing (mirrors GooglePoiDataSource / GooglePoiDiscovery) ----++ private suspend fun warmSession() {+ if (sessionWarmed) return+ runCatching {+ NetworkClient.performRequest(+ url = SESSION_WARM_URL,+ headers = REQUEST_HEADERS + ("Accept" to "text/html,application/xhtml+xml"),+ useSystemTrust = true,+ )+ }+ sessionWarmed = true+ }++ private suspend fun get(url: String): String? {+ val resp = runCatching {+ NetworkClient.performRequest(url = url, headers = REQUEST_HEADERS, useSystemTrust = true)+ }.getOrNull() ?: return null+ return if (resp.isSuccess) resp.body else null+ }++ private fun buildPb(query: String, lat: Double, lon: Double): String =+ SEARCH_PB_TEMPLATE+ .replace("{QUERY}", query.replace('!', ' ').trim())+ .replace("{LNG}", lon.toString())+ .replace("{LAT}", lat.toString())++ private fun String.enc(): String = URLEncoder.encode(this, "UTF-8")++ // Same calibrated pb template as GooglePoiDataSource — the `!2d<lng>!3d<lat>`+ // block centres the search and results come back at [Paths.RESULTS].+ private const val SEARCH_PB_TEMPLATE =+ "!1s{QUERY}!4m8!1m3!1d25229.167291701906!2d{LNG}!3d{LAT}!3m2!1i1024!2i768!4f13.1!7i20" ++ "!10b1!12m52!1m5!18b1!30b1!31m1!1b1!34e1!2m4!5m1!6e2!20e3!39b1!6m25!32i1!49b1!63m0!66b1" ++ "!85b1!114b1!149b1!206b1!209b1!212b1!216b1!222b1!223b1!232b1!234b1!235b1!244b1!246b1" ++ "!250b1!253b1!260b1!266b1!273b1!281b1!291m0!10b1!12b1!13b1!14b1!16b1!17m1!3e1!20m3!5e2" ++ "!6b1!14b1!46m1!1b0!96b1!99b1!19m4!2m3!1i360!2i120!4i8!20m57!2m2!1i203!2i100!3m2!2i4!5b1" ++ "!6m6!1m2!1i86!2i86!1m2!1i408!2i240!7m33!1m3!1e1!2b0!3e3!1m3!1e2!2b1!3e2!1m3!1e2!2b0!3e3" ++ "!1m3!1e8!2b0!3e3!1m3!1e10!2b0!3e3!1m3!1e10!2b1!3e2!1m3!1e10!2b0!3e4!1m3!1e9!2b1!3e2!2b1" ++ "!9b0!15m8!1m7!1m2!1m1!1e2!2m2!1i195!2i195!3i20!15i9937!24m107!1m25!13m9!2b1!3b1!4b1!6i1" ++ "!8b1!9b1!14b1!20b1!25b1!18m14!3b1!4b1!5b1!6b1!13b1!14b1!17b1!21b1!22b1!32b1!33m1!1b1" ++ "!34b1!36e2!10m1!8e3!11m1!3e1!17b1!20m2!1e3!1e6!24b1!25b1!26b1!27b1!29b1!30m1!2b1!36b1" ++ "!37b1!39m3!2m2!2i1!3i1!43b1!52b1!54m1!1b1!55b1!56m1!1b1!61m2!1m1!1e1!65m5!3m4!1m3!1m2" ++ "!1i224!2i298!72m22!1m8!2b1!5b1!7b1!12m4!1b1!2b1!4m1!1e1!4b1!8m10!1m6!4m1!1e1!4m1!1e3" ++ "!4m1!1e4!3sother_user_google_review_posts__and__hotel_and_vr_partner_review_posts!6m1" ++ "!1e1!9b1!89b1!90m2!1m1!1e2!98m3!1b1!2b1!3b1!103b1!113b1!114m3!1b1!2m1!1b1!117b1!122m1" ++ "!1b1!126b1!127b1!128m1!1b0!26m4!2m3!1i80!2i92!4i8!30m28!1m6!1m2!1i0!2i0!2m2!1i530!2i768" ++ "!1m6!1m2!1i974!2i0!2m2!1i1024!2i768!1m6!1m2!1i0!2i0!2m2!1i1024!2i20!1m6!1m2!1i0!2i748" ++ "!2m2!1i1024!2i768!34m19!2b1!3b1!4b1!6b1!8m6!1b1!3b1!4b1!5b1!6b1!7b1!9b1!12b1!14b1!20b1" ++ "!23b1!25b1!26b1!31b1!37m1!1e81!42b1!49m10!3b1!6m2!1b1!2b1!7m2!1e3!2b1!8b1!9b1!10e2!50m3" ++ "!2e2!3m1!3b1!61b1!67m5!7b1!10b1!14b1!15m1!1b0!69i782!77b1"++ // Subset of GooglePoiDataSource.Paths needed for a search row (entry-relative;+ // the place node is [1]; RESULTS/SINGLE are response-root-relative).+ private object Paths {+ val RESULTS = intArrayOf(64)+ val SINGLE = intArrayOf(0, 1, 0, 14)+ val NAME = intArrayOf(1, 11)+ val LAT = intArrayOf(1, 9, 2)+ val LNG = intArrayOf(1, 9, 3)+ val CATEGORY = intArrayOf(1, 13, 0)+ val FEATURE_ID = intArrayOf(1, 10)+ val ADDRESS = intArrayOf(1, 18)+ val ADDRESS_LINES = intArrayOf(1, 2)+ }+}
maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.ktindex 6841d38d01..57df822c85 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt@@ -93,24 +93,6 @@ fun BottomSheetContent( SavedPlaceActions(selectedFeature, savedPlacesViewModel) } }- is SpecificFeature.TransitStop -> {- Column {- TransitStopBottomSheet(inactiveNavigation, selectedFeature) {- if (inactiveNavigation == null) {- setSelectedFeature(SpecificFeature.Route(listOf(null, selectedFeature)))- } else {- setSelectedFeature(- SpecificFeature.Route(- inactiveNavigation.waypoints + listOf(- selectedFeature- )- )- )- }- }- SavedPlaceActions(selectedFeature, savedPlacesViewModel)- }- } is SpecificFeature.Route -> { if(route != null) { RouteSheet(selectedFeature, route, selectedRouteType, setSelectedRouteType, navState)
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 4a95c322ba..53338fefc3 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -72,6 +72,7 @@ import com.vayunmathur.maps.util.OfflineRouter import com.vayunmathur.maps.util.RouteService import com.vayunmathur.maps.util.SavedPlacesViewModel import com.vayunmathur.maps.util.GooglePoiMapViewModel+import com.vayunmathur.maps.util.MapsSearchViewModel import com.vayunmathur.maps.util.SelectedFeatureViewModel import com.vayunmathur.maps.util.ZoneDownloadManager import kotlinx.coroutines.Dispatchers@@ -105,7 +106,7 @@ import com.vayunmathur.maps.R as MapsR @OptIn(ExperimentalMaterial3Api::class) @Composable-fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, zonesViewModel: MapsZonesViewModel, savedPlacesViewModel: SavedPlacesViewModel, poiViewModel: GooglePoiMapViewModel) {+fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, zonesViewModel: MapsZonesViewModel, savedPlacesViewModel: SavedPlacesViewModel, poiViewModel: GooglePoiMapViewModel, searchViewModel: MapsSearchViewModel) { val selectedFeature by viewModel.selectedFeature.collectAsState() val context = LocalContext.current val coroutineScope = rememberCoroutineScope()@@ -117,6 +118,9 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, // suppressed native basemap POIs). val googlePins by poiViewModel.pins.collectAsState() + // Search-result pins (from the Google search page) drawn on the map.+ val searchResults by searchViewModel.results.collectAsState()+ // --- ZONE DOWNLOAD STATE --- val camera = rememberCameraState(CameraPosition(target = Position(-118.243683,34.052235), zoom = 5.0)) @@ -339,22 +343,27 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, GestureOptions.Standard, OrnamentOptions.AllDisabled ),- onMapClick = { _, offset ->+ onMapClick = { latLng, offset -> coroutineScope.launch { val projection = camera.projection- // Hit-test the Google POI overlay first — a pin- // tap re-selects the place as a GenericPlace so+ // Hit-test the search-result pins first, then the+ // ambient Google POI overlay — a pin tap re-selects+ // the place as a GenericPlace so // SelectedFeatureViewModel.currentPoiInfo fetches // the enrichment and GooglePoiEnrichment renders.- val poiHit = projection?.queryRenderedFeatures(+ val pinHit = projection?.queryRenderedFeatures( offset,- setOf(GOOGLE_POI_LAYER_ID)- )?.firstNotNullOfOrNull { it.toSelectedGooglePoi() }- if (poiHit != null) {+ setOf(SEARCH_RESULT_LAYER_ID)+ )?.firstNotNullOfOrNull { it.toSelectedSearchResult() }+ ?: projection?.queryRenderedFeatures(+ offset,+ setOf(GOOGLE_POI_LAYER_ID)+ )?.firstNotNullOfOrNull { it.toSelectedGooglePoi() }+ if (pinHit != null) { if (selectedFeature is SpecificFeature.Route) viewModel.setInactiveNavigation( selectedFeature as SpecificFeature.Route )- viewModel.set(poiHit)+ viewModel.set(pinHit) scaffoldState.bottomSheetState.expand() return@launch }@@ -379,18 +388,32 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, } } - firstFeature?.let {+ if (firstFeature != null) { if (selectedFeature is SpecificFeature.Route) viewModel.setInactiveNavigation( selectedFeature as SpecificFeature.Route )- viewModel.set(it)+ viewModel.set(firstFeature) scaffoldState.bottomSheetState.expand()+ return@launch+ }++ // Nothing hit: reverse-geocode the tapped point+ // ("what's here?"). Replaces the removed address+ // FTS geocoder — online-only (Decision D2).+ searchViewModel.reverseGeocode(latLng.latitude, latLng.longitude) { place ->+ if (place != null) {+ if (selectedFeature is SpecificFeature.Route) viewModel.setInactiveNavigation(+ selectedFeature as SpecificFeature.Route+ )+ viewModel.set(place)+ coroutineScope.launch { scaffoldState.bottomSheetState.expand() }+ } } } ClickResult.Pass } ) {- MyMapLayers(selectedFeature, route?.get(selectedRouteType), json, userPosition, userBearing, navProgress, googlePins)+ MyMapLayers(selectedFeature, route?.get(selectedRouteType), json, userPosition, userBearing, navProgress, googlePins, searchResults) } }
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 fc66e73d80..90ee9bb4cf 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt@@ -17,6 +17,7 @@ import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.data.google.GooglePoiPin import com.vayunmathur.maps.util.OfflineRouter import com.vayunmathur.maps.util.RouteService+import com.vayunmathur.maps.util.SearchResult import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import org.maplibre.compose.expressions.dsl.const@@ -53,6 +54,7 @@ fun MyMapLayers( userBearing: Float, navProgress: com.vayunmathur.maps.util.NavigationProgress? = null, googlePins: List<GooglePoiPin> = emptyList(),+ searchResults: List<SearchResult> = emptyList(), ) { val trafficVersion by OfflineRouter.trafficVersion.collectAsState() val context = LocalContext.current@@ -142,6 +144,10 @@ fun MyMapLayers( // Rendered above traffic but below the user puck. GooglePoiLayer(googlePins) + // Search-result pins (Vela MARKERS_LAYER analog) — drawn above the+ // ambient POI overlay so a query's hits stand out; tap re-selects.+ SearchResultLayer(searchResults)+ userSource?.let { src -> LaunchedEffect(userPosition, userBearing) { src.setData(
maps/src/main/java/com/vayunmathur/maps/ui/RestaurantBottomSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantBottomSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantBottomSheet.ktindex 4a403d9643..6e3ed76cc9 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantBottomSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantBottomSheet.kt@@ -218,34 +218,6 @@ fun RestaurantBottomSheet(viewModel: SelectedFeatureViewModel, inactiveNavigatio } } -@Composable-fun TransitStopBottomSheet(inactiveNavigation: SpecificFeature.Route?, feature: SpecificFeature.TransitStop, requestDirections: () -> Unit) {- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {- Row(verticalAlignment = Alignment.CenterVertically) {- ListItem({- Text(- feature.name,- style = MaterialTheme.typography.titleLarge,- )- }, supportingContent = {- if (feature.stopCode != null || feature.gtfsFeed != null) {- val info = listOfNotNull(feature.gtfsFeed, feature.stopCode).joinToString(" / ")- Text(info)- }- }, trailingContent = {- Button({requestDirections()}) {- if(inactiveNavigation == null) {- Text(stringResource(R.string.directions))- } else {- Text(stringResource(R.string.add_stop_to_route))- }- }- }, colors = ListItemDefaults.colors(containerColor = Color.Transparent))- }- RestaurantItem({ IconGlobe() }, stringResource(R.string.travel_mode_transit)) {}- }-}- fun verticalShape(index: Int, count: Int): RoundedCornerShape { val top = if (index == 0) 12.dp else 0.dp val bottom = if (index == count - 1) 12.dp else 0.dp
maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.ktindex 36bba6f7a2..91b84af454 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt@@ -1,12 +1,18 @@ package com.vayunmathur.maps.ui import androidx.compose.foundation.clickable+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.rememberScrollState+import com.vayunmathur.library.ui.AssistChip import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.HorizontalDivider@@ -26,6 +32,7 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.maps.R import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.ui.IconHistory import com.vayunmathur.library.ui.IconSearch import com.vayunmathur.library.util.round import com.vayunmathur.maps.Route@@ -35,12 +42,12 @@ import com.vayunmathur.maps.util.SearchActions import com.vayunmathur.maps.util.SearchResult import com.vayunmathur.maps.util.SearchUiState import com.vayunmathur.maps.util.SelectedFeatureViewModel-import androidx.compose.ui.platform.LocalContext-import com.vayunmathur.maps.data.AmenityRepository /**- * A Search Page that filters amenities based on a text query and a geographic bounding box.- * Results are dispatched back to the navigation registry upon selection.+ * Google-only search page (amenities.db removed, Decision D2): a text query+ * biased toward the map centre returns Google places, shown Vela-style with+ * quick category chips and a recent-searches list before any text is typed.+ * Results are dispatched back to the navigation registry on selection. */ @Composable fun SearchPage(@@ -53,24 +60,33 @@ fun SearchPage( north: Double, south: Double ) {- val context = LocalContext.current- val repository = remember(context) { AmenityRepository.get(context) } val searchQuery by searchViewModel.query.collectAsState() val results by searchViewModel.results.collectAsState()+ val recents by searchViewModel.recents.collectAsState() - val actions = object : SearchActions {- override fun setQuery(query: String) {- searchViewModel.setQuery(query, repository, west, east, south, north)- }+ // Bias the Google search toward the centre of the visible viewport.+ val nearLat = (north + south) / 2.0+ val nearLon = (east + west) / 2.0++ val actions = remember(nearLat, nearLon, idx) {+ object : SearchActions {+ override fun setQuery(query: String) {+ searchViewModel.setQuery(query, nearLat, nearLon)+ } - override fun selectResult(result: SearchResult) {- // Shared selection path: replace a route waypoint when picking a stop- // (idx != null), otherwise set the selected feature. Then leave the- // search page.- val apply: (SpecificFeature.RoutableFeature) -> Unit = { feature ->+ override fun clearRecents() {+ searchViewModel.clearRecents()+ }++ override fun selectResult(result: SearchResult) {+ searchViewModel.recordRecent(result.title)+ // Shared selection path: replace a route waypoint when picking a+ // stop (idx != null), otherwise set the selected feature. Then+ // leave the search page.+ val feature = searchViewModel.toFeature(result) if (idx != null) {- // The selection could have changed (e.g. user navigated away and- // back) between launching the resolve and the callback firing.+ // The selection could have changed (e.g. user navigated away+ // and back) between opening search and picking a result. // Tolerate a non-Route current selection rather than crashing. val current = viewModel.selectedFeature.value if (current is SpecificFeature.Route) {@@ -85,22 +101,28 @@ fun SearchPage( } backStack.pop() }- when (result) {- is SearchResult.Amenity ->- searchViewModel.resolveAmenity(result.entity, repository) { apply(it) }- is SearchResult.Address ->- apply(searchViewModel.addressFeature(result.result))- }- } - override fun back() {- backStack.pop()+ override fun back() {+ backStack.pop()+ } } } - SearchScreen(SearchUiState(searchQuery, results), actions)+ SearchScreen(SearchUiState(searchQuery, results, recents), actions) } +/** One quick-search category chip: a display label and the query it runs. */+private data class SearchCategory(val labelRes: Int, val query: String)++private val SEARCH_CATEGORIES = listOf(+ SearchCategory(R.string.search_category_restaurants, "restaurants"),+ SearchCategory(R.string.search_category_coffee, "coffee"),+ SearchCategory(R.string.search_category_gas, "gas station"),+ SearchCategory(R.string.search_category_groceries, "groceries"),+ SearchCategory(R.string.search_category_hotels, "hotels"),+ SearchCategory(R.string.search_category_atms, "atm"),+)+ /** The rendered half of [SearchPage]: query text in, results out, no ViewModel. */ @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -123,34 +145,105 @@ fun SearchScreen(state: SearchUiState, actions: SearchActions) { }, onNavigateBack = { actions.back() }, ) { paddingValues ->- Box(modifier = Modifier.padding(paddingValues).fillMaxSize()) {- if (state.results.isEmpty() && state.query.length >= 2) {+ Column(modifier = Modifier.padding(paddingValues).fillMaxSize()) {+ CategoryChips(actions)+ Box(modifier = Modifier.fillMaxSize()) {+ when {+ state.query.length >= 2 && state.results.isEmpty() -> {+ Text(+ text = stringResource(R.string.no_results_found),+ modifier = Modifier.align(Alignment.Center),+ style = MaterialTheme.typography.bodyLarge+ )+ }+ state.query.length >= 2 -> {+ ResultsList(state.results, actions)+ }+ state.recents.isNotEmpty() -> {+ RecentsList(state.recents, actions)+ }+ else -> {+ Text(+ text = stringResource(R.string.type_to_search),+ modifier = Modifier.align(Alignment.Center),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ )+ }+ }+ }+ }+ }+}++@Composable+private fun CategoryChips(actions: SearchActions) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .horizontalScroll(rememberScrollState())+ .padding(horizontal = 16.dp, vertical = 8.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ SEARCH_CATEGORIES.forEach { category ->+ AssistChip(+ onClick = { actions.setQuery(category.query) },+ label = { Text(stringResource(category.labelRes)) },+ )+ }+ }+}++@Composable+private fun ResultsList(results: List<SearchResult>, actions: SearchActions) {+ LazyColumn(modifier = Modifier.fillMaxSize()) {+ items(results, key = { it.id }) { result ->+ ListItem(+ content = { Text(result.title) },+ supportingContent = {+ Text(+ result.subtitle+ ?: stringResource(R.string.coordinates, result.lat.round(4), result.lon.round(4))+ )+ },+ modifier = Modifier.clickable { actions.selectResult(result) }+ )+ HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp))+ }+ }+}++@Composable+private fun RecentsList(recents: List<String>, actions: SearchActions) {+ LazyColumn(modifier = Modifier.fillMaxSize()) {+ item {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 16.dp, vertical = 8.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) { Text(- text = stringResource(R.string.no_results_found),- modifier = Modifier.align(Alignment.Center),- style = MaterialTheme.typography.bodyLarge+ stringResource(R.string.recent_searches),+ style = MaterialTheme.typography.titleSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant, )- } else if (state.query.length < 2) { Text(- text = stringResource(R.string.type_to_search),- modifier = Modifier.align(Alignment.Center),- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant+ stringResource(R.string.clear_recents),+ style = MaterialTheme.typography.labelLarge,+ color = MaterialTheme.colorScheme.primary,+ modifier = Modifier.clickable { actions.clearRecents() }, )- } else {- LazyColumn(modifier = Modifier.fillMaxSize()) {- items(state.results, key = { it.key }) { result ->- ListItem(- content = { Text(result.title.ifBlank { stringResource(R.string.unnamed_amenity) }) },- supportingContent = {- Text(stringResource(R.string.coordinates, result.lat.round(4), result.lon.round(4)))- },- modifier = Modifier.clickable { actions.selectResult(result) }- )- HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp))- }- } } }+ items(recents, key = { it }) { recent ->+ ListItem(+ content = { Text(recent) },+ leadingContent = { IconHistory() },+ modifier = Modifier.clickable { actions.setQuery(recent) }+ )+ HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp))+ } } }
maps/src/main/java/com/vayunmathur/maps/ui/SearchResultLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/SearchResultLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/SearchResultLayer.ktnew file mode 100644index 0000000000..ba2a85825d--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/SearchResultLayer.kt@@ -0,0 +1,138 @@+package com.vayunmathur.maps.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+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.SearchResult+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.doubleOrNull+import kotlinx.serialization.json.jsonPrimitive+import org.maplibre.compose.expressions.dsl.const+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.zoom+import org.maplibre.compose.layers.CircleLayer+import org.maplibre.compose.layers.SymbolLayer+import org.maplibre.compose.sources.GeoJsonData+import org.maplibre.compose.sources.GeoJsonOptions+import org.maplibre.compose.sources.GeoJsonSource+import org.maplibre.compose.util.MaplibreComposable+import org.maplibre.spatialk.geojson.FeatureCollection+import org.maplibre.spatialk.geojson.Point+import org.maplibre.spatialk.geojson.Position++/** Symbol layer id — hit-tested in MapPage.onMapClick (before the ambient POI+ * layer) so a tapped search pin re-selects that place. */+const val SEARCH_RESULT_LAYER_ID = "search-result-pins"+private const val SEARCH_RESULT_DOT_LAYER_ID = "search-result-dots"+private const val SEARCH_RESULT_SOURCE_ID = "search-result-geojson"++/**+ * Search-result pin overlay (Vela's `MARKERS_LAYER` analog): a [GeoJsonSource]+ * fed from the Google search results plus a [CircleLayer] "dot" and a+ * [SymbolLayer] marker glyph on top, ported to maplibre-compose declarative+ * layers exactly like [GooglePoiLayer]. Distinct from the ambient POI overlay so+ * search pins read as "your results" (a single accent colour) rather than the+ * category-coloured ambient POIs. Tap → details via [toSelectedSearchResult].+ */+@Composable+@MaplibreComposable+fun SearchResultLayer(results: List<SearchResult>) {+ val marker = remember { generateSearchMarkerBitmap() }+ var source by remember { mutableStateOf<GeoJsonSource?>(null) }++ LaunchedEffect(Unit) {+ source = GeoJsonSource(+ SEARCH_RESULT_SOURCE_ID,+ GeoJsonData.Features(FeatureCollection(emptyList<Feature1>())),+ GeoJsonOptions(),+ )+ }++ source?.let { src ->+ LaunchedEffect(results) {+ src.setData(GeoJsonData.Features(FeatureCollection(results.map { it.toFeature() })))+ }++ CircleLayer(+ SEARCH_RESULT_DOT_LAYER_ID,+ src,+ color = const(Color(0xFFEA4335)),+ radius = interpolate(+ linear(), zoom(),+ 11 to const(5.dp),+ 14 to const(7.dp),+ 17 to const(9.dp),+ ),+ strokeColor = const(Color.White),+ strokeWidth = const(2.dp),+ )++ SymbolLayer(+ SEARCH_RESULT_LAYER_ID,+ src,+ iconImage = image(marker),+ iconSize = interpolate(+ linear(), zoom(),+ 11 to const(0.4f),+ 14 to const(0.55f),+ 17 to const(0.7f),+ ),+ )+ }+}++/** Rebuild a result as a GeoJSON point feature; name/lat/lon ride along so+ * onMapClick can re-select the place. */+private fun SearchResult.toFeature(): Feature1 = Feature1(+ Point(Position(lon, lat)),+ JsonObject(+ mapOf(+ "id" to JsonPrimitive(id),+ "name" to JsonPrimitive(title),+ "lat" to JsonPrimitive(lat),+ "lng" to JsonPrimitive(lon),+ "category" to JsonPrimitive(category ?: ""),+ )+ ),+)++/**+ * Convert a hit-tested search pin feature back into a selectable place, reusing+ * [SpecificFeature.GenericPlace] so the existing+ * `SelectedFeatureViewModel.currentPoiInfo` flow fetches the Google enrichment+ * and `GooglePoiEnrichment` renders in the sheet — no new detail path needed.+ */+fun Feature1.toSelectedSearchResult(): SpecificFeature? {+ val props = properties ?: return null+ 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))+}++/** Draw the search marker once: a white-ringed accent dot used as the+ * SymbolLayer glyph on top of the base circle. */+private fun generateSearchMarkerBitmap(): ImageBitmap {+ val size = 48+ 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 / 6f, paint)+ return bmp.asImageBitmap()+}
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 9f6e183ce0..fe5c2093a4 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt@@ -3,82 +3,78 @@ package com.vayunmathur.maps.util import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope-import com.vayunmathur.maps.data.AddressResult-import com.vayunmathur.maps.data.AmenityRepository-import com.vayunmathur.maps.data.AmenityEntity-import com.vayunmathur.maps.data.OpeningHours+import com.vayunmathur.maps.data.RecentSearchStore import com.vayunmathur.maps.data.SpecificFeature-import kotlinx.coroutines.Dispatchers+import com.vayunmathur.maps.data.google.GoogleSearchDataSource+import com.vayunmathur.maps.data.google.GoogleSearchResult import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted 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 /**- * A single row in the search list. The one search box returns both nearby named- * amenities and free-text address matches, so results are a mix of the two.+ * A single row in the search list. Since search is now Google-only (Decision D2,+ * amenities.db removed), every result is one Google place: a title, an optional+ * subtitle (address or category) and a position, so it can both fill the list+ * row and drop a pin on the map. */-sealed interface SearchResult {- val key: String- val title: String- val lat: Double- val lon: Double+data class SearchResult(+ val id: String,+ val title: String,+ val subtitle: String?,+ val lat: Double,+ val lon: Double,+ val category: String?,+) - data class Amenity(val entity: AmenityEntity) : SearchResult {- override val key get() = "amenity:${entity.id}"- override val title get() = entity.name- override val lat get() = entity.lat- override val lon get() = entity.lon- }-- data class Address(val result: AddressResult) : SearchResult {- override val key get() = "address:${result.id}"- override val title get() = result.address- override val lat get() = result.lat- override val lon get() = result.lon- }-}+private fun GoogleSearchResult.toSearchResult() = SearchResult(+ id = id,+ title = name,+ subtitle = address ?: category,+ lat = lat,+ lon = lng,+ category = category,+) /** * Owns the text query and result list for the maps search page. *- * The viewport bounding box is supplied per-query because it is determined by- * the camera in the calling composable; we don't observe it as state.+ * Results come from the keyless Google scrape ([GoogleSearchDataSource]); the map+ * centre is supplied per-query by the calling composable to bias the search. The+ * results flow is also observed by `MapPage` to draw the search-result pin layer. */ class MapsSearchViewModel(application: Application) : AndroidViewModel(application) { + private val recentStore = RecentSearchStore.get(application)+ private val _query = MutableStateFlow("") val query: StateFlow<String> = _query.asStateFlow() private val _results = MutableStateFlow<List<SearchResult>>(emptyList()) val results: StateFlow<List<SearchResult>> = _results.asStateFlow() - /** In-flight search job — cancelled on each new keystroke so old DB queries- * don't race ahead of newer ones and overwrite the result list. */+ /** Recent queries, most-recent first, for the pre-search suggestions. */+ val recents: StateFlow<List<String>> = recentStore.recents+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), recentStore.current())++ /** In-flight search job — cancelled on each new keystroke so an older scrape+ * doesn't race ahead of a newer one and overwrite the result list. */ private var searchJob: Job? = null /**- * Updates the search text and (asynchronously) the result list. Named- * amenities are matched within the current viewport [west]..[east] /- * [south]..[north]; addresses are matched globally so you can jump to one- * that isn't currently on screen. Queries shorter than two characters clear- * the results without hitting the DB.+ * Updates the search text and (asynchronously) the result list via the Google+ * scrape, biased toward [nearLat],[nearLon] (the map centre). Queries shorter+ * than two characters clear the results without hitting the network. *- * Debounced ~120 ms so fast typists don't stack a query per keystroke; the- * previous job is cancelled on every call.+ * Debounced ~250 ms (Decision D7) so fast typists don't stack a scrape per+ * keystroke; the previous job is cancelled on every call. */- fun setQuery(- query: String,- repository: AmenityRepository,- west: Double,- east: Double,- south: Double,- north: Double,- ) {+ fun setQuery(query: String, nearLat: Double, nearLon: Double) { _query.value = query searchJob?.cancel() if (query.length < 2) {@@ -86,106 +82,65 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati return } searchJob = viewModelScope.launch {- delay(120)- // Amenities: all prefix tokens must match (AND) so "blue bot" ->- // "Blue Bottle". Addresses: any prefix token may match (OR) and- // bm25 ranks the closest, giving fuzzy "closest match" behaviour.- val amenityQuery = ftsPrefixQuery(query, " ")- val addressQuery = ftsPrefixQuery(query, " OR ")- if (amenityQuery.isEmpty()) {- _results.value = emptyList()- return@launch- }- val merged = withContext(Dispatchers.IO) {- val amenities = repository.getInBBox(- query = amenityQuery,- latMin = south,- latMax = north,- lonMin = west,- lonMax = east,- ).map { SearchResult.Amenity(it) }- val addresses = repository.searchAddresses(addressQuery)- .map { SearchResult.Address(it) }- amenities + addresses- }- _results.value = merged+ delay(250)+ // GoogleSearchDataSource.search does its own Dispatchers.IO + never+ // throws (empty list on any scrape/path failure).+ _results.value = GoogleSearchDataSource.search(query, nearLat, nearLon)+ .map { it.toSearchResult() } } } - /** Resets the search state. */- fun setQuery(- query: String,- db: com.vayunmathur.maps.data.AmenityDatabase,- west: Double,- east: Double,- south: Double,- north: Double,- ) = setQuery(query, AmenityRepository.get(getApplication()), west, east, south, north)-- fun resolveAmenity(- amenity: AmenityEntity,- db: com.vayunmathur.maps.data.AmenityDatabase,- onFeature: (SpecificFeature.Restaurant) -> Unit,- ) = resolveAmenity(amenity, AmenityRepository.get(getApplication()), onFeature)-+ /** Resets the search state (keeps recents). */ fun reset() { searchJob?.cancel() _query.value = "" _results.value = emptyList() } - /**- * Loads tags for [amenity], builds a [SpecificFeature.Restaurant], and- * invokes [onFeature] back on the main thread. The launch runs in- * `viewModelScope` so a navigation-away mid-resolve cleanly cancels the- * callback rather than calling back into a stale UI.- */- fun resolveAmenity(- amenity: AmenityEntity,- repository: AmenityRepository,- onFeature: (SpecificFeature.Restaurant) -> Unit,- ) {- viewModelScope.launch {- val tags = withContext(Dispatchers.IO) {- repository.getTags(amenity.id).associate { it.key to it.value }- }- val feature = SpecificFeature.Restaurant(- name = tags["name"] ?: "",- phone = tags["phone"],- website = tags["website"],- menu = tags["website:menu"],- openingHours = tags["opening_hours"]?.let { OpeningHours.from(it) },- position = Position(amenity.lon, amenity.lat),- )- onFeature(feature)- }+ /** Record a committed query in the recents store. */+ fun recordRecent(query: String) {+ viewModelScope.launch { recentStore.add(query) }+ }++ fun clearRecents() {+ viewModelScope.launch { recentStore.clear() } } /**- * Builds a [SpecificFeature.GenericPlace] for an address hit. Addresses- * carry no OSM tags, so this is a plain place (name = the address string)- * that flows through the same selection path as an amenity.+ * Build a [SpecificFeature.GenericPlace] for a picked search result. It flows+ * through the same selection path as a tapped map pin, so+ * `SelectedFeatureViewModel.currentPoiInfo` then fetches the Google+ * enrichment for the sheet. */- fun addressFeature(address: AddressResult): SpecificFeature.GenericPlace =+ fun toFeature(result: SearchResult): SpecificFeature.GenericPlace = SpecificFeature.GenericPlace(- name = address.address,+ name = result.title, phone = null, website = null, openingHours = null,- position = Position(address.lon, address.lat),+ position = Position(result.lon, result.lat), )-} -/**- * Turns free-text into an FTS5 expression. Splits on non-alphanumeric- * characters, lowercases, and turns each token into a prefix term (`market*`),- * joined by [joiner] (" " for AND, " OR " for OR). Returns "" when there are no- * usable tokens.- */-private fun ftsPrefixQuery(raw: String, joiner: String): String {- val tokens = raw.lowercase()- .split(Regex("[^\\p{L}\\p{N}]+"))- .filter { it.isNotBlank() }- if (tokens.isEmpty()) return ""- return tokens.joinToString(joiner) { "$it*" }+ /**+ * Reverse-geocode [lat],[lon] to the nearest addressable place and hand it+ * back as a [SpecificFeature.GenericPlace] (or null when there's no match).+ * Replaces the removed address FTS geocoder; used for "what's here?" taps on+ * empty map (Decision D2 — online-only).+ */+ fun reverseGeocode(lat: Double, lon: Double, onResult: (SpecificFeature.GenericPlace?) -> Unit) {+ viewModelScope.launch {+ val hit = GoogleSearchDataSource.reverseGeocode(lat, lon)+ onResult(+ hit?.let {+ SpecificFeature.GenericPlace(+ 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/MapsUiContract.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapsUiContract.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapsUiContract.ktindex 8ed3e37ba3..eb688a32cf 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapsUiContract.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapsUiContract.kt@@ -17,19 +17,21 @@ package com.vayunmathur.maps.util data class SearchUiState( val query: String = "", val results: List<SearchResult> = emptyList(),+ val recents: List<String> = emptyList(), ) /** * Search callbacks. Every method has a no-op default so a preview can render the screen * without supplying behaviour — [Noop] is the whole implementation a preview needs. *- * These are not implemented by [MapsSearchViewModel]: a query needs the amenity database- * and the visible bounding box, and picking a result touches the nav back stack, so the- * search page builds the adapter itself.+ * These are not implemented by [MapsSearchViewModel]: a query needs the visible bounding+ * box (to bias the Google search toward the map centre) and picking a result touches the+ * nav back stack, so the search page builds the adapter itself. */ interface SearchActions { fun setQuery(query: String) {} fun selectResult(result: SearchResult) {}+ fun clearRecents() {} fun back() {} companion object {
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 6794695ecf..c0ff46c12f 100644--- a/maps/src/main/res/values/strings.xml+++ b/maps/src/main/res/values/strings.xml@@ -29,8 +29,22 @@ <string name="no_results_found">No results found in this area</string> <!-- SearchPage: Helper text prompting user to type --> <string name="type_to_search">Type at least 2 characters to search</string>- <!-- SearchPage: Fallback name when OSM amenity has no name. Noun. -->- <string name="unnamed_amenity">Unnamed Amenity</string>+ <!-- SearchPage: Header above the recent-searches list. Noun. -->+ <string name="recent_searches">Recent</string>+ <!-- SearchPage: Button clearing the recent-searches list. Verb. -->+ <string name="clear_recents">Clear</string>+ <!-- SearchPage: Quick category chip — eating places. Noun. -->+ <string name="search_category_restaurants">Restaurants</string>+ <!-- SearchPage: Quick category chip — coffee shops. Noun. -->+ <string name="search_category_coffee">Coffee</string>+ <!-- SearchPage: Quick category chip — fuel/charging stations. Noun. -->+ <string name="search_category_gas">Gas</string>+ <!-- SearchPage: Quick category chip — grocery stores. Noun. -->+ <string name="search_category_groceries">Groceries</string>+ <!-- SearchPage: Quick category chip — hotels/lodging. Noun. -->+ <string name="search_category_hotels">Hotels</string>+ <!-- SearchPage: Quick category chip — cash machines. Noun. -->+ <string name="search_category_atms">ATMs</string> <!-- SearchPage: Displays lat/lon. %1$s=latitude e.g. "37.7749", %2$s=longitude e.g. "-122.4194" --> <string name="coordinates">Coordinates: <xliff:g id="latitude" example="37.7749">%1$s</xliff:g>, <xliff:g id="longitude" example="-122.4194">%2$s</xliff:g></string> @@ -106,8 +120,6 @@ <!-- Button: Remove Work saved place --> <string name="remove_from_work">Remove from Work</string> - <!-- MainActivity: Status text while amenity DB downloads -->- <string name="downloading_amenity_database">Downloading Amenity Database…</string> <!-- MainActivity: Status text while navigation tiling metadata downloads --> <string name="downloading_navigation_metadata">Downloading Navigation Tiling Metadata…</string> <!-- MainActivity: Status text while road data downloads -->
maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/MetadataPreviews.kt
diff --git a/maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/MetadataPreviews.kt b/maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/MetadataPreviews.ktindex cde7d70ac1..9ced387432 100644--- a/maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/MetadataPreviews.kt+++ b/maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/MetadataPreviews.kt@@ -11,8 +11,6 @@ import com.android.tools.screenshot.PreviewTest import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Surface-import com.vayunmathur.maps.data.AddressResult-import com.vayunmathur.maps.data.AmenityEntity import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.util.NavigationProgress import com.vayunmathur.maps.util.NavigationSessionManager@@ -83,24 +81,10 @@ class MetadataPreviews { SearchUiState( query = "ferry", results = listOf(- SearchResult.Amenity(- AmenityEntity(1, "Ferry Building Marketplace", 37.7955, -122.3933)- ),- SearchResult.Amenity(- AmenityEntity(2, "Ferry Plaza Farmers Market", 37.7959, -122.3937)- ),- SearchResult.Amenity(- AmenityEntity(3, "Golden Gate Ferry Terminal", 37.7936, -122.3927)- ),- SearchResult.Amenity(- AmenityEntity(4, "Oakland Ferry Dock", 37.7947, -122.2783)- ),- SearchResult.Address(- AddressResult(5, "1 Ferry Building, San Francisco", 37.7955, -122.3937)- ),- SearchResult.Address(- AddressResult(6, "480 Ferry Point, Richmond", 37.9099, -122.3608)- ),+ SearchResult("1", "Ferry Building Marketplace", "1 Ferry Building, San Francisco", 37.7955, -122.3933, "Marketplace"),+ SearchResult("2", "Ferry Plaza Farmers Market", "1 Ferry Building, San Francisco", 37.7959, -122.3937, "Farmers market"),+ SearchResult("3", "Golden Gate Ferry Terminal", "Pier 1, San Francisco", 37.7936, -122.3927, "Ferry terminal"),+ SearchResult("4", "Oakland Ferry Dock", "Clay St, Oakland", 37.7947, -122.2783, "Ferry terminal"), ), ), SearchActions.Noop,