Modern Apps git

← Modern-Apps.git

maps: delete google traffic tiles, search goes osm-only

Commit
0df91c91fde87edc7ad592461c72756b0adf016d
Author
vayun-mathur <[email protected]>
When
2026-10-23 20:33 UTC (1 month ago)
Parents
86c2d98

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 5417fae6c3..acd1fe9625 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -27,7 +27,6 @@ import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.maps.data.MapLink import com.vayunmathur.maps.data.MapLinkParser import com.vayunmathur.maps.data.SpecificFeature-import com.vayunmathur.maps.data.google.GoogleSearchDataSource import com.vayunmathur.maps.ui.MapPage import com.vayunmathur.maps.ui.SavedPlacesPage import com.vayunmathur.maps.ui.settings.MapSettingsPage@@ -213,9 +212,21 @@ class MainActivity : MaActivity() {                 destName = link.query ?: getString(R.string.dropped_pin)             } else if (!link.query.isNullOrBlank()) {                 val near = biasPosition()-                val hit = GoogleSearchDataSource.search(link.query, near.latitude, near.longitude).firstOrNull()-                destPos = hit?.let { GeoPoint(it.lng, it.lat) }-                destName = hit?.name ?: link.query+                // Offline OSM POI search (no query-bar side effects: this path+                // must not prefill the search text like searchAndSelectFirst+                // does). Free-text addresses have no OSM path and stay+                // unresolvable, handled below.+                val query = link.query+                val first = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {+                    runCatching {+                        com.vayunmathur.maps.util.PoiIndex.initialize(applicationContext)+                        com.vayunmathur.maps.util.PoiIndex.searchByName(+                            query, near.latitude, near.longitude, limit = 1,+                        ).firstOrNull()+                    }.getOrNull()+                }+                destPos = first?.let { GeoPoint(it.lon, it.lat) }+                destName = first?.name ?: query             } else {                 destPos = null                 destName = getString(R.string.dropped_pin)
maps/src/main/java/com/vayunmathur/maps/car/CarSearchScreen.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/car/CarSearchScreen.kt b/maps/src/main/java/com/vayunmathur/maps/car/CarSearchScreen.ktindex 60314906e6..ad6032f397 100644--- a/maps/src/main/java/com/vayunmathur/maps/car/CarSearchScreen.kt+++ b/maps/src/main/java/com/vayunmathur/maps/car/CarSearchScreen.kt@@ -28,8 +28,8 @@ import androidx.lifecycle.LifecycleOwner import com.vayunmathur.maps.R import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.maps.data.SpecificFeature-import com.vayunmathur.maps.data.google.GoogleSearchDataSource-import com.vayunmathur.maps.data.google.GoogleSearchResult+import com.vayunmathur.maps.util.PoiCategories+import com.vayunmathur.maps.util.PoiIndex import com.vayunmathur.maps.util.NavigationService import com.vayunmathur.maps.util.NavigationSessionManager import com.vayunmathur.maps.util.OfflineRouterRoadRoutes@@ -38,6 +38,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel+import kotlinx.coroutines.withContext import kotlinx.coroutines.launch import com.vayunmathur.library.map.GeoPoint @@ -47,8 +48,8 @@ import com.vayunmathur.library.map.GeoPoint  * Voice-first: the Search action launches the **system** [SpeechRecognizer]  * (the OS routes it to the user-selected recognition service — the same  * system-STT path P8 uses on the phone via `VoiceSearchButton`), and the final- * transcript is fed to the existing keyless [GoogleSearchDataSource] (P3). Hits- * are shown in a [MapWithContentTemplate] (list + map markers); tapping a+ * transcript is fed to the offline OSM POI index ([PoiIndex.searchByName]).+ * Hits are shown in a [MapWithContentTemplate] (list + map markers); tapping a  * result routes to it with the existing [OfflineRouter], starts the shared  * [NavigationSessionManager] + [NavigationService], and returns to the map  * screen where turn-by-turn takes over.@@ -58,7 +59,7 @@ import com.vayunmathur.library.map.GeoPoint  */ class CarSearchScreen(carContext: CarContext) : Screen(carContext) { -    private var results: List<GoogleSearchResult> = emptyList()+    private var results: List<PoiIndex.PoiRecord> = emptyList()     private var loading = false     private var message: String? = null     private var recognizer: SpeechRecognizer? = null@@ -119,11 +120,11 @@ class CarSearchScreen(carContext: CarContext) : Screen(carContext) {         } else {             for (r in results) {                 val row = Row.Builder().setTitle(r.name)-                val subtitle = r.address ?: r.category-                if (!subtitle.isNullOrBlank()) row.addText(subtitle)+                val subtitle = PoiCategories.label(r.type)+                if (subtitle.isNotBlank()) row.addText(subtitle)                 row.setMetadata(                     Metadata.Builder()-                        .setPlace(Place.Builder(CarLocation.create(r.lat, r.lng)).build())+                        .setPlace(Place.Builder(CarLocation.create(r.lat, r.lon)).build())                         .build()                 )                 row.setOnClickListener { startNavigationTo(r) }@@ -194,22 +195,26 @@ class CarSearchScreen(carContext: CarContext) : Screen(carContext) {         loading = true         message = carContext.getString(R.string.car_searching)         invalidate()-        scope.launch {-            val hits = GoogleSearchDataSource.search(-                query,-                near?.latitude ?: 0.0,-                near?.longitude ?: 0.0,-            )+        scope.launch(kotlinx.coroutines.Dispatchers.IO) {+            val hits = runCatching {+                PoiIndex.initialize(carContext)+                PoiIndex.searchByName(+                    query,+                    near?.latitude ?: 0.0,+                    near?.longitude ?: 0.0,+                    limit = 20,+                )+            }.getOrDefault(emptyList())             results = hits             loading = false             message = if (hits.isEmpty()) {                 carContext.getString(R.string.car_no_results)             } else null-            invalidate()+            withContext(kotlinx.coroutines.Dispatchers.Main) { invalidate() }         }     } -    private fun startNavigationTo(result: GoogleSearchResult) {+    private fun startNavigationTo(result: PoiIndex.PoiRecord) {         val userPos = lastKnownPosition()         if (userPos == null) {             message = carContext.getString(R.string.car_route_failed)@@ -219,7 +224,7 @@ class CarSearchScreen(carContext: CarContext) : Screen(carContext) {         loading = true         invalidate()         scope.launch {-            val dest = GeoPoint(longitude = result.lng, latitude = result.lat)+            val dest = GeoPoint(longitude = result.lon, latitude = result.lat)             val routeFeature = SpecificFeature.Route(                 listOf(                     null, // first waypoint = current position (getRouteMulti fills it)
maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDiscovery.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDiscovery.kt b/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDiscovery.ktdeleted file mode 100644index f06ec2c36a..0000000000--- a/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDiscovery.kt+++ /dev/null@@ -1,330 +0,0 @@-package com.vayunmathur.maps.data.google--import com.vayunmathur.library.log.Log-import com.vayunmathur.library.network.NetworkClient-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.async-import kotlinx.coroutines.awaitAll-import kotlinx.coroutines.coroutineScope-import kotlinx.coroutines.sync.Semaphore-import kotlinx.coroutines.sync.withPermit-import kotlinx.coroutines.withContext-import kotlinx.serialization.json.JsonElement-import java.net.URLEncoder-import kotlin.math.cos-import kotlin.math.hypot-import kotlin.math.ln-import kotlin.math.log2--/**- * Viewport / near discovery of Google POIs for the custom overlay layer.- *- * This generalises [GooglePoiDataSource]'s single-place `pickEntry`/`parsePlace`- * (which collapse the scraped result set to the one nearest match): instead we- * keep the WHOLE list and map each entry to a [GooglePoiPin] (id + lat/lng +- * name + category + rating) so the pins can be drawn and tapped.- *- * COVERAGE: a- * single wide "points of interest" query returns only the ~20 most prominent- * places over a ~25 km baked window, so a strip mall shows almost none of its- * small businesses. To match what Google Maps actually renders we instead:- *  - TIGHTEN the requested viewport to the caller's real span (`!1d` = span in- *    metres, `!4f` = the matching zoom) instead of the baked ~25 km net;- *  - FAN OUT across category terms ("restaurants", "coffee", "gas station", …)- *    and merge — one "places" query is biased to prominent food/shops and misses- *    whole tiers (a nail salon, a plumber, a small taqueria), so the fan-out- *    roughly doubles local coverage;- *  - ask for a DEEPER pool per term (`!7i60`, up from 20) so the take-N cap can- *    reach smaller POIs;- *  - dedup by feature id and rank prominence-first,- *    so recognizable landmarks win the label slot but the small restaurant you- *    zoomed next to still survives the (raised) cap.- *- * Same keyless google.com/maps scrape caveats as [GooglePoiDataSource]: it calls- * the same undocumented `search?tbm=map` endpoint a logged-out browser hits (no- * API key), the response is a guard-prefixed positional JSON array parsed by 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].- *- * Quota-safe (D3/D7/P23): the ViewModel debounces the camera trigger and floors- * a min-interval, results are LRU-cached here per viewport centre + span so a- * small pan back into a visited area doesn't refetch, and the per-fetch category- * fan-out is bounded by [FANOUT] permits so a fresh viewport fires only a few- * requests at a time rather than all terms at once.- *- * 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 GooglePoiDiscovery {--    private const val TAG = "GooglePoiDiscovery"--    // Same calibrated endpoints/identity as GooglePoiDataSource (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/",-    )--    /**-     * Category fan-out terms. "places" is the-     * broad ambient query; the rest pull the tiers a single prominent-biased-     * query under-returns so the map shows a Google-like MIX (a gas station, a-     * gym, a grocer, a small restaurant) rather than only the few big names.-     * Low-signal extras a term drags in sink under the prominence sort.-     */-    private val FANOUT_TERMS = listOf(-        "places", "restaurants", "coffee", "stores", "shopping", "services",-        "beauty salon", "fast food", "grocery store", "gas station", "gym",-        "bar", "pharmacy", "school", "park",-    )--    /** Caps how many category requests run AT ONCE per fetch, so a fresh viewport-     *  doesn't fire all [FANOUT_TERMS] at once (request burst + transient parse-     *  heap). Shared across calls so a pan mid-load can't double the burst. */-    private val FANOUT = Semaphore(4)--    /** Default cap on pins per fetch. The full ranked pool is cached, so a-     *  close-zoom caller can pass a higher cap to keep smaller POIs without a-     *  refetch (see [GooglePoiMapViewModel]). Raised well above the old 60 so the-     *  fan-out's comprehensive pool isn't filtered back down to a few names. */-    private const val MAX_PINS = 120--    /** Per-term result pool. Deeper than the old !7i20 so zooming in can reach-     *  down the prominence rank to small/local POIs. */-    private const val POOL_SIZE = 60--    /** Clamp for the requested ground span (`!1d`). Floored so a very tight zoom-     *  still asks a sensible window; capped so a wide view doesn't request a-     *  continent. */-    private const val MIN_SPAN_M = 500.0-    private const val MAX_SPAN_M = 40_000.0-    /** Cache span bucket (m): centres in the same bucket share a cache entry. */-    private const val SPAN_BUCKET_M = 250.0-    /** Zoom matched to [BASE_SPAN_M], the template's baked window. */-    private const val BASE_ZOOM = 13.1-    private const val BASE_SPAN_M = 25229.0-    private const val MIN_ZOOM = 13.0-    private const val MAX_ZOOM = 17.5-    /** Prominence weights: review count dominates (log-compressed), rating nudges. */-    private const val RATING_WEIGHT = 0.6-    private const val DEFAULT_RATING = 3.5-    private const val RATING_SCALE = 10.0-    /** Scale for rounding cache keys to ~100 m. */-    private const val ROUND_SCALE = 1000.0-    /** Metres per degree of latitude, for the rank-tiebreak distance. */-    private const val METERS_PER_DEGREE = 111_320.0--    @Volatile private var sessionWarmed = false--    // Bounded access-ordered LRU keyed on rounded centre + span bucket. The FULL-    // ranked pool is stored so a higher-cap caller reuses it. Guarded by-    // synchronized(cache).-    private data class Key(val lat: Double, val lon: Double, val spanBucket: Int)-    private val cache = object : LinkedHashMap<Key, List<GooglePoiPin>>(16, 0.75f, true) {-        override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Key, List<GooglePoiPin>>) = size > 32-    }--    /**-     * Discover POIs around [lat],[lon] within a viewport of [spanMeters] ground-     * span. Never throws — returns an empty list when the scrape fails or the-     * positional paths drift. LRU-cached on the centre (rounded to ~100 m) plus-     * a span bucket so re-visiting an area is instant.-     *-     * [maxPins] caps how many of the ranked pins are returned. The full ranked-     * pool is cached, so a close-zoom caller can ask for many more without a-     * refetch — easing the prominence filter so smaller POIs aren't cut.-     */-    suspend fun nearby(-        lat: Double,-        lon: Double,-        spanMeters: Double,-        maxPins: Int = MAX_PINS,-    ): List<GooglePoiPin> {-        val span = spanMeters.coerceIn(MIN_SPAN_M, MAX_SPAN_M)-        val key = Key(round3(lat), round3(lon), (span / SPAN_BUCKET_M).toInt())-        synchronized(cache) { cache[key]?.let { return it.take(maxPins) } }-        val pins = runCatching { fetch(lat, lon, span) }.getOrDefault(emptyList())-        synchronized(cache) { cache[key] = pins }-        Log.status(-            TAG,-            "nearby lat=$lat lon=$lon span=${span.toInt()}m terms=${FANOUT_TERMS.size} " +-                "pool=${pins.size} returned=${minOf(pins.size, maxPins)} (cap=$maxPins)",-        )-        return pins.take(maxPins)-    }--    /**-     * Fan out the [FANOUT_TERMS] across the viewport, merge, dedup by feature id-     * and rank prominence-first. Each term is a separate keyless `search?tbm=map`-     * hit with the viewport tightened to [span]; any single term failing/​drifting-     * yields an empty list for that term and never sinks the others.-     */-    private suspend fun fetch(lat: Double, lon: Double, span: Double): List<GooglePoiPin> =-        withContext(Dispatchers.IO) {-            warmSession()-            // Match the zoom to the tightened window (span 25229 ↔ zoom 13.1).-            val zoom = (BASE_ZOOM + log2(BASE_SPAN_M / span)).coerceIn(MIN_ZOOM, MAX_ZOOM)-            val pool = coroutineScope {-                FANOUT_TERMS.map { term ->-                    async { runCatching { fetchTerm(term, lat, lon, span, zoom) }.getOrDefault(emptyList()) }-                }.awaitAll().flatten()-            }-            rank(pool, lat, lon)-        }--    private suspend fun fetchTerm(-        term: String,-        lat: Double,-        lon: Double,-        span: Double,-        zoom: Double,-    ): List<GooglePoiPin> = FANOUT.withPermit {-        val pb = buildViewportPb(term, lat, lon, span, zoom)-        val url = "$SEARCH_ENDPOINT&q=${term.enc()}&pb=${pb.enc()}"-        val body = get(url) ?: return@withPermit emptyList()-        val root = GoogleResponse.parseOrNull(body) ?: return@withPermit emptyList()-        parsePins(root)-    }--    /**-     * The list-returning generalisation of `pickEntry`/`parsePlace`: walk every-     * result entry at [Paths.RESULTS] and pull the pin fields. Entries missing a-     * name or position are dropped.-     */-    private fun parsePins(root: JsonElement): List<GooglePoiPin> {-        val list = root.at(*Paths.RESULTS).arr() ?: return emptyList()-        return list.mapNotNull { entry ->-            val name = entry.at(*Paths.NAME).str() ?: return@mapNotNull null-            val plat = entry.at(*Paths.LAT).dbl() ?: return@mapNotNull null-            val plng = entry.at(*Paths.LNG).dbl() ?: return@mapNotNull null-            val rating = entry.at(*Paths.RATING).dbl()-            val reviews = entry.at(*Paths.REVIEW_COUNT).int() ?: 0-            GooglePoiPin(-                id = entry.at(*Paths.FEATURE_ID).str() ?: "$plat,$plng",-                name = name,-                lat = plat,-                lng = plng,-                category = entry.at(*Paths.CATEGORY).str(),-                rating = rating,-                prominence = prominenceOf(rating, reviews),-            )-        }-    }--    /**-     * Dedup by feature id (the same place returned under several terms) then rank-     * for the map: prominence-first, exact distance from the viewport centre only-     * as a tiebreak. The recognizable landmarks lead-     * and win the label slot; the low-signal junk the fan-out drags in sinks and-     * is dropped by the caller's take-N cap.-     */-    private fun rank(pool: List<GooglePoiPin>, lat: Double, lon: Double): List<GooglePoiPin> =-        pool.distinctBy { it.id }-            .sortedWith(-                compareByDescending<GooglePoiPin> { it.prominence }-                    .thenBy { metersBetween(lat, lon, it.lat, it.lng) },-            )--    /** Prominence score: review count dominates (log-compressed so a-     *  mega-chain doesn't utterly bury everything), nudged by rating so among-     *  similarly-popular places the better-rated wins. */-    private fun prominenceOf(rating: Double?, reviews: Int): Double =-        ln(reviews.coerceAtLeast(0) + 1.0) * (RATING_WEIGHT + (rating ?: DEFAULT_RATING) / RATING_SCALE)--    // --- HTTP plumbing (mirrors GooglePoiDataSource) --------------------------    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-    }--    /** Build the viewport `pb`: substitute the query + centre, then tighten the-     *  baked span/zoom/pool tokens to this fetch: `!1d` =-     *  ground span in metres, `!4f` = matching zoom, `!7i` = the deeper pool. */-    private fun buildViewportPb(-        query: String,-        lat: Double,-        lon: Double,-        span: Double,-        zoom: Double,-    ): String =-        SEARCH_PB_TEMPLATE-            .replace("{QUERY}", query.replace('!', ' ').trim())-            .replace("{LNG}", lon.toString())-            .replace("{LAT}", lat.toString())-            .replaceFirst(Regex("!1d[0-9.]+"), "!1d${span.toInt()}")-            .replaceFirst(Regex("!4f[0-9.]+"), "!4f${String.format(java.util.Locale.US, "%.1f", zoom)}")-            .replaceFirst(Regex("!7i\\d+"), "!7i$POOL_SIZE")--    private fun round3(v: Double): Double = Math.round(v * ROUND_SCALE) / ROUND_SCALE-    private fun String.enc(): String = URLEncoder.encode(this, "UTF-8")--    /** Rough planar metres between two lat/lon points — enough for a rank-     *  tiebreak at viewport scale; no need for full haversine here. */-    private fun metersBetween(aLat: Double, aLon: Double, bLat: Double, bLon: Double): Double {-        val mPerDegLat = METERS_PER_DEGREE-        val dLat = (bLat - aLat) * mPerDegLat-        val dLon = (bLon - aLon) * mPerDegLat * cos(Math.toRadians((aLat + bLat) / 2.0))-        return hypot(dLat, dLon)-    }--    // Same calibrated pb template as GooglePoiDataSource — the `!2d<lng>!3d<lat>`-    // block centres the viewport; the `!1d`/`!4f`/`!7i` tokens are rewritten-    // per-fetch (see buildViewportPb) 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 pin (entry-relative; the-    // place node is [1], RESULTS is response-root-relative).-    private object Paths {-        val RESULTS = intArrayOf(64)-        val NAME = intArrayOf(1, 11)-        val LAT = intArrayOf(1, 9, 2)-        val LNG = intArrayOf(1, 9, 3)-        val CATEGORY = intArrayOf(1, 13, 0)-        val RATING = intArrayOf(1, 4, 7)-        val REVIEW_COUNT = intArrayOf(1, 4, 8)-        val FEATURE_ID = intArrayOf(1, 10)-    }-}
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.ktdeleted file mode 100644index 0309200eb0..0000000000--- a/maps/src/main/java/com/vayunmathur/maps/data/google/GoogleSearchDataSource.kt+++ /dev/null@@ -1,244 +0,0 @@-package com.vayunmathur.maps.data.google--import com.vayunmathur.library.log.Log-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 {--    private const val TAG = "GoogleSearchDataSource"--    // Same calibrated endpoints/identity as GooglePoiDataSource (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 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()-        val results = runCatching { fetchSearch(query, nearLat, nearLon) }.getOrDefault(emptyList())-        Log.status(-            TAG,-            "search \"$query\" near $nearLat,$nearLon -> ${results.size} results" +-                (results.firstOrNull()?.let { " first=\"${it.name}\"@${it.lat},${it.lng}" } ?: ""),-        )-        return results-    }--    /**-     * 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()-            resolveEntries(root)-                .mapNotNull { entry -> entryToResult(entry) }-                .distinctBy { it.id }-                .take(MAX_RESULTS)-        }--    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-            resolveEntries(root).firstNotNullOfOrNull { entry -> entryToResult(entry) }-        }--    /**-     * Resolve the response to a list of result *entries* whose place node is at-     * `[1]`, mirroring the resolution order so an ADDRESS-     * query resolves too (not just POI names/categories):-     *  1. the `[64]` POI list — a name/category search ("restaurants");-     *  2. [Paths.AT_THIS_PLACE] — a bare address that IS a business ("1020 Olive-     *     Dr" → the In-N-Out at it); the businesses at the geocoded address, each-     *     entry's node at `[i][0]`;-     *  3. [Paths.SINGLE] — a plain/far address that geocodes to one node.-     * Cases 2/3 wrap the node as `[null, node]` so the entry-relative paths-     * (place node at `[1]`) resolve unchanged. Empty when nothing matched.-     */-    private fun resolveEntries(root: JsonElement): List<JsonElement> {-        root.at(*Paths.RESULTS).arr()?.takeIf { it.isNotEmpty() }?.let { return it }-        atThisPlaceEntries(root)?.let { return it }-        singleEntry(root)?.let { return listOf(it) }-        return emptyList()-    }--    /** Businesses AT a geocoded address ([Paths.AT_THIS_PLACE]): each list entry's-     *  place node is at `[i][0]`; wrap as [null, node] and gate on a real name. */-    private fun atThisPlaceEntries(root: JsonElement): List<JsonElement>? {-        val list = root.at(*Paths.AT_THIS_PLACE).arr() ?: return null-        val entries = list.mapNotNull { e ->-            val node = e.at(0) ?: return@mapNotNull null-            val entry = JsonArray(listOf(JsonNull, node))-            if (entry.at(*Paths.NAME).str() == null) return@mapNotNull null-            entry-        }-        return entries.ifEmpty { null }-    }--    /** A single geocoded node ([Paths.SINGLE]) → wrap as [null, node] so the-     *  entry-relative paths (place node at [1]) resolve unchanged; null when the-     *  wrapped node carries no name. */-    private fun singleEntry(root: JsonElement): JsonElement? {-        val node = root.at(*Paths.SINGLE) ?: return null-        val entry = JsonArray(listOf(JsonNull, node))-        return if (entry.at(*Paths.NAME).str() != null) entry else null-    }--    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)-        // Businesses listed at a geocoded address.-        val AT_THIS_PLACE = intArrayOf(0, 1, 0, 14, 68)-        // Full formatted address ([1][39]); ADDRESS_LINES is the-        // component array fallback.-        val ADDRESS = intArrayOf(1, 39)-        val ADDRESS_LINES = intArrayOf(1, 2)-    }-}
maps/src/main/java/com/vayunmathur/maps/data/google/GoogleTrafficSource.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/google/GoogleTrafficSource.kt b/maps/src/main/java/com/vayunmathur/maps/data/google/GoogleTrafficSource.ktdeleted file mode 100644index ff2c8a5948..0000000000--- a/maps/src/main/java/com/vayunmathur/maps/data/google/GoogleTrafficSource.kt+++ /dev/null@@ -1,89 +0,0 @@-package com.vayunmathur.maps.data.google--import com.vayunmathur.library.network.NetworkClient-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.withContext--/**- * Keyless Google Maps live-traffic raster tiles.- *- * Replaces the old on-device OfflineRouter loopback vector-traffic tile server- * (`http://localhost/traffic/{z}/{x}/{y}`) with Google's own colored congestion- * overlay — the same transparent raster tiles maps.google.com layers over its- * basemap when Traffic is turned on.- *- * ENDPOINT: the web map's own `/maps/vt` tile on `www.google.com` — a public,- * keyless PNG on the same host the other `data/google` scrapes already use. The- * tile is selected by a trimmed protobuf `pb` param (no map-version epoch, so it- * doesn't rot):- *  - `!1m4!1m3!1i{z}!2i{x}!3i{y}` — standard XYZ tile coords (z, then x, then y);- *  - `!2m9!1e2!2straffic` — `!1e2` = overlay layer, `!2straffic` = the traffic- *    layer (transparent everywhere there's no congestion data);- *  - the trailing `!4m2!1sincidents…` block enables incident markers, and the- *    `!3m8!2sen!3sus…!2sRoadmap` block pins language/region + roadmap styling.- * This is the exact tile URL the logged-out web map fetches, so it needs no API- * key, session token, or referer — a plain GET returns the PNG. A bad/blocked- * tile degrades to a transparent gap, never a crash.- *- * Two ways to consume it:- *  - [TILE_URLS] / [tileTemplate] — the `{x}`/`{y}`/`{z}` raster template for a- *    raster layer source, once the renderer can draw one (currently a GAP: the- *    phone map keeps this as a no-op and the toggle plumbing survives).- *  - [tile] (z,x,y) → PNG bytes — a manual keyless fetch mirroring- *    [StreetViewDataSource.tile], for callers that need the bytes directly.- *- * NOTE (on-device): live tiles need a device with network — they can't be- * exercised at compile time.- */-object GoogleTrafficSource {--    /** Google's `/maps/vt` PNG tiles are 256 px (vs the 512 px vector basemap). */-    const val TILE_SIZE = 256--    // The trimmed `pb` spec selecting Google's live-traffic overlay tile. Kept as-    // a template with `{z}`/`{x}`/`{y}` tokens (order matters: `!1i{z}!2i{x}!3i{y}`)-    // so a future raster-layer source and the manual [tile] fetch build the same URL.-    private const val TILE_PB =-        "https://www.google.com/maps/vt/pb=!1m4!1m3!1i{z}!2i{x}!3i{y}!2m9!1e2!2straffic!3i999999" +-            "!4m2!1sincidents!2s1!4m2!1sincidents_text!2s1!3m8!2sen!3sus!5e1105!12m4!1e68!2m2!1sset!2sRoadmap!4e0!5m1!1e0"--    /** `{x}`/`{y}`/`{z}` raster template — a raster-layer source substitutes the-    *  tokens per requested tile, once the renderer can draw one. */-    fun tileTemplate(): String = TILE_PB--    /** The traffic tile URL as a single-element raster-source tile list. */-    val TILE_URLS: List<String> = listOf(TILE_PB)--    val available: Boolean get() = TILE_URLS.isNotEmpty()--    /** Success range for the tile fetch. */-    private const val HTTP_OK_MIN = 200-    private const val HTTP_OK_MAX = 299--    // Browser-like identity for the manual [tile] path. The `/maps/vt` endpoint is-    // keyless and serves the PNG to a plain GET, but sending the same headers as-    // the other google scrapes keeps the direct-bytes fetch consistent.-    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/",-    )--    /**-     * Fetch one traffic tile's PNG bytes, or null on any non-2xx / transport-     * error / empty body. Never throws.-     */-    suspend fun tile(z: Int, x: Int, y: Int): ByteArray? = withContext(Dispatchers.IO) {-        val url = TILE_PB-            .replace("{z}", z.toString())-            .replace("{x}", x.toString())-            .replace("{y}", y.toString())-        val (status, bytes) = runCatching {-            NetworkClient.performRequestBytes(url = url, headers = REQUEST_HEADERS, useSystemTrust = true)-        }.getOrNull() ?: return@withContext null-        if (status in HTTP_OK_MIN..HTTP_OK_MAX && bytes.isNotEmpty()) bytes else null-    }-}
maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.ktindex 678bad942e..49a1567d24 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt@@ -22,7 +22,7 @@ import java.time.OffsetDateTime  * to fall back to `/api/v1/plan`; the on-device RAPTOR planner is now the only  * planner.  *- * Design mirrors [com.vayunmathur.maps.data.google.GooglePoiDiscovery]:+ * Design mirrors the (since removed) GooglePoiDiscovery shape:  *  - an `object` singleton, all network on [Dispatchers.IO];  *  - **never throws** — every public call returns empty on any failure so a  *    flaky feed or a MOTIS schema drift degrades gracefully;@@ -88,7 +88,7 @@ object TransitousDataSource {     }      private suspend fun fetchDepartures(stopId: String): List<Departure> = withContext(Dispatchers.IO) {-        // Proxied via self-hosted (maps/.../TransitBoards mirrors GooglePoiDiscovery):+        // Proxied via self-hosted (same object-singleton shape as the retired Google fetchers):         // server forwards to api.transitous.org/api/v1/stoptimes with a short cache.         // arriveBy is fixed false server-side — the only value this client uses.         val url = "$BASE_URL/stoptimes" +
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 86e1a75c48..6e4da6abcf 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt@@ -272,9 +272,9 @@ private fun PlaceTabPanel( /**  * 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.+ * New surface: nothing displayed an address before — search rows only ever+ * showed a category subtitle. Tapping copies it, which is what an address on+ * a sheet is usually for.  */ @Composable private fun AddressRow(address: String) {
maps/src/main/java/com/vayunmathur/maps/util/GooglePoiMapViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/GooglePoiMapViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/GooglePoiMapViewModel.ktindex a3e51b7750..2a4ffce7a0 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/GooglePoiMapViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/GooglePoiMapViewModel.kt@@ -3,89 +3,33 @@ package com.vayunmathur.maps.util import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope-import com.vayunmathur.maps.data.google.GooglePoiDiscovery import com.vayunmathur.maps.data.google.GooglePoiPin import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow-import kotlinx.coroutines.flow.collectLatest-import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.math.abs-import kotlin.math.cos-import kotlin.math.hypot  /**- * Drives the custom Google-POI overlay: turns viewport boxes into a debounced,- * LRU-cached list of [GooglePoiPin]s to render (Decisions D3/D7, snappier P23).+ * Drives the ambient POI overlay: turns viewport boxes into a debounced list+ * of [GooglePoiPin]s to render (Decisions D3/D7, snappier P23), sourced from+ * the offline OSM POI index (P29). No network.  *- * [onViewport] is fed from `MapPage` as the camera MOVES (not only on idle). To- * keep the overlay feeling live without hammering the keyless scrape, the driver:- *  - keeps the previous pins on screen until a *new, non-empty* fetch returns- *    (an empty/degraded scrape never blinks the overlay to nothing);- *  - fetches with a short debounce when the centre jumps past [BIG_MOVE_M] and a- *    gentler one otherwise, floored by a [MIN_INTERVAL_MS] min-interval;- *  - prefetches a padded ([PREFETCH_SCALE]) bbox so a small pan is already- *    covered, and merges results by pin id (pruning ones panned out of the padded- *    box) so shared pins stay stable instead of flickering;- *  - still skips wide views (> ~16 km, [MAX_LAT_SPAN]) where POI pins are- *    meaningless. All network is on [Dispatchers.IO].+ * The driver keeps the previous pins on screen until a *new, non-empty*+ * lookup returns (an empty index never blinks the overlay to nothing),+ * debounces fast pans, and still skips wide views (> ~16 km, [MAX_LAT_SPAN])+ * where POI pins are meaningless. All index reads are on [Dispatchers.IO].  */ class GooglePoiMapViewModel(application: Application) : AndroidViewModel(application) {      private val _pins = MutableStateFlow<List<GooglePoiPin>>(emptyList())     val pins: StateFlow<List<GooglePoiPin>> = _pins.asStateFlow() -    private data class Viewport(-        val lat: Double,-        val lon: Double,-        val north: Double,-        val east: Double,-        val south: Double,-        val west: Double,-    )--    // Latest requested viewport; null suppresses fetching (zoomed out) while-    // leaving the current pins on screen.-    private val _viewport = MutableStateFlow<Viewport?>(null)--    // Pins currently shown, keyed by id so a refresh keeps shared pins stable-    // (no blink) and merely adds/removes the delta. Guarded by synchronized.-    private val shown = LinkedHashMap<String, GooglePoiPin>()--    private var lastFetchCenter: Pair<Double, Double>? = null-    private var lastFetchAt = 0L--    @OptIn(ExperimentalCoroutinesApi::class)-    private fun start() {-        viewModelScope.launch {-            _viewport.filterNotNull().collectLatest { vp ->-                // Snappier on a big jump (short debounce); gentle on small nudges.-                // collectLatest cancels this delay when a newer viewport arrives,-                // giving the debounce for free.-                val movedM = lastFetchCenter?.let {-                    metersBetween(it.first, it.second, vp.lat, vp.lon)-                } ?: Double.MAX_VALUE-                delay(if (movedM >= BIG_MOVE_M) SHORT_DEBOUNCE_MS else DEBOUNCE_MS)-                // Min-interval floor so a fast pan can't machine-gun the scrape.-                val since = System.currentTimeMillis() - lastFetchAt-                if (since < MIN_INTERVAL_MS) delay(MIN_INTERVAL_MS - since)-                fetch(vp)-            }-        }-    }--    init {-        start()-    }--    // Offline ambient-pin refresh (P29), separate from the retired Google-scrape-    // pipeline above. Cancelled on each new viewport so a fast pan debounces.+    // Ambient-pin refresh job. Cancelled on each new viewport so a fast pan debounces.     private var offlineJob: Job? = null      /**@@ -115,68 +59,13 @@ class GooglePoiMapViewModel(application: Application) : AndroidViewModel(applica      /**      * Feed a viewport (from `queryVisibleBoundingBox()`). Views wider than-     * [MAX_LAT_SPAN] suppress fetching but KEEP the last pins (no clear);-     * otherwise the box drives the next (debounced, min-intervalled) fetch.+     * [MAX_LAT_SPAN] are ignored, keeping the last pins (no clear).+     *+     * The retired Google-scrape entry point kept its name so former callers+     * stay compilable during migration; it forwards to [onViewportOffline].      */     fun onViewport(north: Double, east: Double, south: Double, west: Double) {-        if (abs(north - south) > MAX_LAT_SPAN) {-            _viewport.value = null-            return-        }-        _viewport.value = Viewport(-            lat = (north + south) / 2.0,-            lon = (east + west) / 2.0,-            north = north,-            east = east,-            south = south,-            west = west,-        )-    }--    private suspend fun fetch(vp: Viewport) {-        // Derive a rough zoom band from the viewport's latitude span (we're only-        // fed the bbox). At close zoom, query the ACTUAL (tight) viewport with-        // little padding so a POI you zoomed next to isn't washed out by a wider,-        // prominence-ranked box, and keep many more of the returned pins so-        // local/small POIs (restaurants) survive. Farther out, prefetch a padded-        // box so small pans are pre-covered.-        val closeZoom = abs(vp.north - vp.south) <= CLOSE_LAT_SPAN-        val prefetchScale = if (closeZoom) TIGHT_SCALE else PREFETCH_SCALE-        val cap = if (closeZoom) MAX_PINS_CLOSE else MAX_PINS_FAR--        // The (padded, per-zoom) ground span the fan-out should request — the-        // vertical extent of the box scaled by the prefetch pad, in metres.-        // `!1d` is tightened to this so a strip mall's small POIs come back instead of-        // only the ~20 most prominent over a baked ~25 km window.-        val spanMeters = (vp.north - vp.south) * prefetchScale * METERS_PER_DEG_LAT--        val pins = withContext(Dispatchers.IO) {-            GooglePoiDiscovery.nearby(vp.lat, vp.lon, spanMeters = spanMeters, maxPins = cap)-        }-        lastFetchCenter = vp.lat to vp.lon-        lastFetchAt = System.currentTimeMillis()-        // Empty result (scrape miss / bot-degraded): keep the existing pins so-        // the overlay never blinks to empty.-        if (pins.isEmpty()) return--        // Prune shown pins to the (padded, per-zoom) box so old areas don't-        // accumulate; at close zoom the pad is ~0 so we track the tight viewport.-        val padLat = (vp.north - vp.south) * (prefetchScale - 1.0) / 2.0-        val padLon = (vp.east - vp.west) * (prefetchScale - 1.0) / 2.0-        val north = vp.north + padLat-        val south = vp.south - padLat-        val east = vp.east + padLon-        val west = vp.west - padLon--        synchronized(shown) {-            val iter = shown.entries.iterator()-            while (iter.hasNext()) {-                val p = iter.next().value-                if (p.lat !in south..north || p.lng !in west..east) iter.remove()-            }-            for (p in pins) shown[p.id] = p-            _pins.value = shown.values.toList()-        }+        onViewportOffline(north, east, south, west)     }      /** Map an offline index record to the pin model [pins] publishes; the@@ -189,58 +78,15 @@ class GooglePoiMapViewModel(application: Application) : AndroidViewModel(applica         category = PoiCategories.label(type),     ) -    /** Rough planar metres between two lat/lon points — enough for a move-     *  threshold; no need for full haversine at these small spans. */-    private fun metersBetween(aLat: Double, aLon: Double, bLat: Double, bLon: Double): Double {-        val mPerDegLat = 111_320.0-        val dLat = (bLat - aLat) * mPerDegLat-        val dLon = (bLon - aLon) * mPerDegLat * cos(Math.toRadians((aLat + bLat) / 2.0))-        return hypot(dLat, dLon)-    }-     private companion object {         // Idle-ish refresh for small nudges.         const val DEBOUNCE_MS = 350L -        // Faster refresh once the centre jumps a meaningful distance.-        const val SHORT_DEBOUNCE_MS = 120L--        // Never fetch more often than this, however fast the camera moves.-        const val MIN_INTERVAL_MS = 700L--        // "Big move" threshold (metres) that earns the short debounce.-        const val BIG_MOVE_M = 1_200.0--        // Fetch a padded bbox (~1.8x the viewport) so small pans are pre-covered.-        // Used at medium/far zoom; close zoom uses the tight box below.-        const val PREFETCH_SCALE = 1.8--        // Close zoom: query the actual viewport with only a hair of padding so a-        // POI you zoomed next to isn't dropped in favour of wider, more prominent-        // ones.-        const val TIGHT_SCALE = 1.1--        // Latitude span (~4.4 km) at/under which we treat the view as "close" and-        // switch to the tight box + higher cap.-        const val CLOSE_LAT_SPAN = 0.04--        // Pin caps: keep a modest cap when zoomed out, but raise it a lot at-        // close zoom so local/small POIs (restaurants) from the category fan-out-        // aren't filtered away. Raised from the old 60/200 now that the fetch-        // returns a comprehensive Google-like pool rather than ~20 prominent-        // names.-        const val MAX_PINS_FAR = 120-        const val MAX_PINS_CLOSE = 350--        // ~16 km of latitude — roughly city-zoom; wider views skip the scrape.+        // ~16 km of latitude — roughly city-zoom; wider views skip the lookup.         const val MAX_LAT_SPAN = 0.15          // Cap on ambient offline pins per viewport (P29) so a dense city box         // stays bounded; matches the ambient overlay's close-zoom feel.         const val OFFLINE_CAP = 300--        // Degrees of latitude → metres, for turning the viewport's lat span into-        // the ground span the discovery fetch tightens its `!1d` window to.-        const val METERS_PER_DEG_LAT = 111_320.0     } }
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 3fe3ff8543..2a1e773b3f 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt@@ -6,8 +6,6 @@ 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 import kotlinx.coroutines.Job import kotlinx.coroutines.delay@@ -21,10 +19,9 @@ import kotlinx.coroutines.withContext import com.vayunmathur.library.map.GeoPoint  /**- * 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.+ * A single row in the search list. Results come from the offline OSM POI+ * index: a title, an optional subtitle (category) and a position, so it can+ * both fill the list row and drop a pin on the map.  */ data class SearchResult(     val id: String,@@ -35,15 +32,6 @@ data class SearchResult(     val category: String?, ) -private fun GoogleSearchResult.toSearchResult() = SearchResult(-    id = id,-    title = name,-    subtitle = address ?: category,-    lat = lat,-    lon = lng,-    category = category,-)- private fun PoiIndex.PoiRecord.toSearchResult() = SearchResult(     id = "poi:$latE7:$lonE7:${name.hashCode()}",     title = name,@@ -56,7 +44,7 @@ private fun PoiIndex.PoiRecord.toSearchResult() = SearchResult( /**  * Owns the text query and result list for the maps search page.  *- * Results come from the keyless Google scrape ([GoogleSearchDataSource]); the map+ * Results come from the offline OSM POI index ([PoiIndex.searchByName]); 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.  */@@ -96,11 +84,11 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati     private var searchJob: Job? = null      /**-     * 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.+     * Updates the search text and (asynchronously) the result list from the+     * offline OSM POI index, biased toward [nearLat],[nearLon] (the map centre).+     * Queries shorter than two characters clear the results without searching.      *-     * Debounced ~250 ms (Decision D7) so fast typists don't stack a scrape per+     * Debounced ~250 ms (Decision D7) so fast typists don't stack a search per      * keystroke; the previous job is cancelled on every call.      */     fun setQuery(query: String, nearLat: Double, nearLon: Double) {@@ -117,11 +105,9 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati         searchJob = viewModelScope.launch {             try {                 delay(SEARCH_DEBOUNCE_MS)-                // Try the offline OSM POI index first (P27): resolving a POI name-                // locally avoids a Google call. Google stays the fallback (and-                // handles addresses, which the POI index doesn't carry). Any offline-                // failure (unmapped/poisoned index, decode error) is swallowed so the-                // query still falls through to Google.+                // Offline OSM POI index only (P27). Addresses are not carried by+                // the index, so they resolve to empty. Any offline failure+                // (unmapped/poisoned index, decode error) is swallowed to empty.                 val app = getApplication<Application>()                 val offline = withContext(Dispatchers.IO) {                     runCatching {@@ -129,14 +115,7 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati                         PoiIndex.searchByName(query, nearLat, nearLon, limit = 20)                     }.getOrDefault(emptyList())                 }-                if (offline.isNotEmpty()) {-                    _results.value = offline.map { it.toSearchResult() }-                    return@launch-                }-                // GoogleSearchDataSource.search does its own Dispatchers.IO + never-                // throws (empty list on any scrape/path failure).-                _results.value = GoogleSearchDataSource.search(query, nearLat, nearLon)-                    .map { it.toSearchResult() }+                _results.value = offline.map { it.toSearchResult() }             } finally {                 // `finally` because cancellation is the normal exit: every keystroke cancels                 // the previous job, and a cancelled search that never clears this flag leaves@@ -147,13 +126,14 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati     }      /**-     * Runs the Google search for [query] immediately (no debounce), publishes the-     * results so the list + map pins update, and hands back the FIRST result (or-     * null) so a caller can auto-select it programmatically.+     * Runs the offline OSM search for [query] immediately (no debounce),+     * publishes the results so the list + map pins update, and hands back the+     * FIRST result (or null) so a caller can auto-select it programmatically.      *-     * Used by the P17 contact-address shortcut: pick an address → search → open+     * Used by the P17 contact-address shortcut: pick a POI name → search → open      * the top hit without a user tap. Cancels any in-flight keystroke search-     * first so results don't race.+     * first so results don't race. Free-text addresses have no OSM path and+     * resolve to null.      */     fun searchAndSelectFirst(         query: String,@@ -164,10 +144,13 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati         _query.value = query         searchJob?.cancel()         searchJob = viewModelScope.launch {-            // GoogleSearchDataSource.search does its own Dispatchers.IO + never-            // throws (empty list on any scrape/path failure).-            val results = GoogleSearchDataSource.search(query, nearLat, nearLon)-                .map { it.toSearchResult() }+            val app = getApplication<Application>()+            val results = withContext(Dispatchers.IO) {+                runCatching {+                    PoiIndex.initialize(app)+                    PoiIndex.searchByName(query, nearLat, nearLon, limit = 20)+                }.getOrDefault(emptyList())+            }.map { it.toSearchResult() }             _results.value = results             onFirst(results.firstOrNull())         }@@ -181,12 +164,10 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati      * [_query] or populate [_results] (that would prefill the search bar and      * draw the search-result pins).      *-     * A full address string is resolved via the Google text [GoogleSearchDataSource.search]-     * (the only path that maps a string to a coordinate; [reverseGeocode] takes a-     * coordinate, not an address). The search does its own [Dispatchers.IO] and-     * never throws; [onResolved] fires on the main thread so the caller can-     * safely drive [SelectedFeatureViewModel.selectAndFocus]. Returns null when-     * nothing resolves.+     * Offline-only: a POI-name query resolves through the OSM index; a full+     * postal address has no OSM path and resolves to null. [onResolved] fires+     * on the main thread so the caller can safely drive+     * [SelectedFeatureViewModel.selectAndFocus].      */     fun resolveAndSelect(         address: String,@@ -199,16 +180,19 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati             return         }         viewModelScope.launch {-            val hit = GoogleSearchDataSource.search(address, nearLat, nearLon).firstOrNull()-            onResolved(-                hit?.let {-                    osmPlace(-                        name = it.name.ifBlank { it.address ?: address },-                        position = GeoPoint(it.lng, it.lat),-                        poiType = null,-                    )-                }-            )+            // Reuse the POI-name path: named places resolve, street addresses+            // (which the OSM index doesn't carry) resolve to null.+            searchAndSelectFirst(address, nearLat, nearLon) { first ->+                onResolved(+                    first?.let {+                        osmPlace(+                            name = it.title.ifBlank { address },+                            position = GeoPoint(it.lon, it.lat),+                            poiType = null,+                        )+                    }+                )+            }         }     } @@ -230,11 +214,9 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati      /**      * 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.+     * through the same selection path as a tapped map pin.      *-     * The sidecar lookup matters most here: an offline result has no Google+     * The sidecar lookup matters most here: an offline result has no remote      * enrichment coming, so without it the sheet opens with a title and nothing      * else. It is also a mapped-file read, hence [osmPlace] and this suspend.      */@@ -242,19 +224,25 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati         osmPlace(name = result.title, position = GeoPoint(result.lon, result.lat))      /**-     * 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).+     * Reverse-geocode [lat],[lon] to the nearest offline POI and hand it back+     * as a [SpecificFeature.GenericPlace] (or null when nothing is nearby).+     * Used for "what's here?" taps on empty map. Street addresses have no OSM+     * path — the result is the nearest named POI within 250 m, or null.      */     fun reverseGeocode(lat: Double, lon: Double, onResult: (SpecificFeature.GenericPlace?) -> Unit) {         viewModelScope.launch {-            val hit = GoogleSearchDataSource.reverseGeocode(lat, lon)+            val app = getApplication<Application>()+            val hit = withContext(Dispatchers.IO) {+                runCatching {+                    PoiIndex.initialize(app)+                    PoiIndex.nearest(lat, lon, limit = 1).firstOrNull()+                }.getOrNull()+            }             onResult(                 hit?.let {                     osmPlace(-                        name = it.name.ifBlank { it.address ?: "" },-                        position = GeoPoint(it.lng, it.lat),+                        name = it.name,+                        position = GeoPoint(it.lon, it.lat),                     )                 }             )