maps P1: Google-only amenity overlay layer + suppress native POIs
- Commit
0b5af5a91cd58cd14ba451f71e9109a24a04e494- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-16 22:11 UTC (3 months ago)
- Parents
410a73b
Diff
maps/VELA_PORT_PLAN.md
diff --git a/maps/VELA_PORT_PLAN.md b/maps/VELA_PORT_PLAN.mdnew file mode 100644index 0000000000..0c69e4072b--- /dev/null+++ b/maps/VELA_PORT_PLAN.md@@ -0,0 +1,186 @@+# Vela → Modern-Apps Maps: Port Plan (Research + Plan only)++Scope: port Vela's UI/layout, driving/turn-by-turn nav UI, and missing features into the **existing** Modern-Apps (MA) maps app; rework amenities to be **Google-only** on a **custom overlay layer**.++**KEEP (do not replace):** MA's MapLibre/PMTiles **renderer**, MA's on-device Rust **routing** engine + live-nav stack, and the already-added Google POI enrichment (`data/google/` + `PoiEnrichment.kt`).+**Voice:** system TTS only (MA already has `NavigationTts.kt`); do **not** port Vela's Piper/neural synth.+**Lint:** `RawScaffoldInApp` → use shared `library/ui` scaffolds; trademark strings ("Google", etc.) stay non-translatable.++Vela paths below are relative to the clone root (removed after research; never committed). MA paths are under `maps/src/main/java/com/vayunmathur/maps/`.++---++## (a) Vela inventory — UI / driving nav / POI layer (file refs)++**Renderer (matches MA family):** MapLibre Native `org.maplibre.gl:android-sdk:11.8.0`, imperative API (not Compose bindings). Base style = OpenFreeMap Liberty (OMT schema) remote URL. `core/.../data/tiles/MapStyle.kt`. PMTiles used for overlays (buildings, maxspeed, offline regions).++**Map view / renderer wrapper:** `app/.../ui/map/VelaMapView.kt` (6013 lines) — the imperative MapLibre wrapper. Key mechanics:+- **Suppress native basemap POIs:** set `visibility = NONE` on Liberty POI layers `poi_r1, poi_r7, poi_r20, poi_transit` (`VelaMapView.kt:781-788`, re-asserted in `applyData` ~`:1150-1195`).+- **Custom Google-POI overlay ("ambient"):** `GeoJsonSource AMBIENT_SRC` + `SymbolLayer AMBIENT_LAYER` (icons) + `AMBIENT_DOT_LAYER` (dots) built at `:3234-3345`; category icons from `PoiIcons` (`vela-poi-<group>` runtime bitmaps). Consts `:139-143`, `:183`.+- **Search-result pins:** `GeoJsonSource MARKERS_SRC` + `SymbolLayer MARKERS_LAYER`/`MARKERS_DOTS_LAYER` (`:3140-3160`). Model `data class MapMarker(name, location, category, prominence, rating, fuelPrice)` (`:221`).+- **Tap handling:** `handleTap` (`:1857-2004`) → `map.queryRenderedFeatures(RectF, layers…)`; priority parking → own pins (`MARKER_INDEX_PROP`) → saved → GTFS stop → **ambient Google vs basemap POI by screen distance** (`:1905-1946`) → house-number → building; fires `onAmbientTap(index)` / `markerTap(index)` / `onPoiTap(name, latlng, kind)`. Registered `map.addOnMapClickListener { handleTap(it) }` (`:2004`).+- **Nav camera:** heading-up + tilt + close follow, eased; two-finger tilt/shove, re-center tick to drop overrides (`:283-292, :481-540, :585-640, :1215-1290`). Uses `CameraPosition.bearing/tilt`.+- **Posted speed limit:** poll `queryRenderedFeatures` on hosted **maxspeed PMTiles** overlay under the puck (`:967-1003`), parsed by `core/.../data/OsmMaxspeed.kt`.+- POI icon factory: `app/.../ui/map/PoiIcons.kt` — `applyToLiberty` (`:435`), `resultIconKey/resultBubbleLabel`, `ensureResultIcon`, `addResultDot`, `colorFor(group)`, `GROUPS` category→color/glyph map.++**Map screen layout:** `app/.../ui/map/MapScreen.kt` (259 KB) — `MapScreen(...)`, `SearchResults`, `CategoryChips`, `ChooseOnMapOverlay`, `SearchEntryContent`, shortcut/saved rows, `SpeedWidget` (speedometer), `ScaleBarReader`, cards (voice/region download, faster-route, notices), `ListsSheet`. Scale bar: `app/.../ui/map/ScaleBar.kt`. Layers button: `app/.../ui/LayersButton.kt`. Compass toggle wired via `onCompassTap` (north-up/heading-up during drive).++**Search UX:** `app/.../ui/search/SearchBar.kt` (`SearchBar(...)`), results/chips in `MapScreen.SearchResults`/`CategoryChips`. Geocode/search data via Google source (below) + `core/.../data/PhotonGeocoder.kt`, `RecentSearchStore`, `CategoryFilter.kt`.++**Place-details sheet:** `app/.../ui/place/PlaceSheet.kt` (235 KB) — `PlaceSheet`, `DirectionsPanel`, `RouteOption`, photos gallery, reviews, hours, popular times, transit boards. Support: `RouteTopCard.kt`, `StopsEditor.kt`, `PlaceContent.kt`, `RatingStars.kt`, `LiveReviews.kt`.++**Driving / turn-by-turn nav UI:** `app/.../ui/nav/`+- `NavOverlays.kt` (42 KB): `ManeuverBanner` (with `FitText`), `LaneGuide`/`LaneDiagram` (lane arrows), `SignChip`/`roadSigns` (road shields), `NavControls`, `ArrivalSummary`, `NavSearchChips`.+- `RouteShield.kt`: US route/state shields (`RouteShield`, `ShieldBadge`, `StateMarker`).+- `StepsSheet.kt`: full turn list (`StepsSheet`, `maneuverIcon`).+- Speedometer + posted limit: `MapScreen.SpeedWidget` + `app/.../ui/Format.kt formatSpeedLimit`.+- Nav logic (reference only — MA keeps its own): `core/.../nav/NavEngine.kt`, `NavSession.kt`, `NavModels.kt`, `Heading.kt`.+- Voice: `core/.../voice/VoiceGuide.kt` uses **Android `TextToSpeech`** as primary (`import android.speech.tts.TextToSpeech`); Piper/`NeuralSynth`/`PiperCatalog`/`VelaPiper` are the optional neural path we **skip**. Guidance text: `SpokenScript.kt`, `SpeechText.kt`.++**Google data source (reference for search + POIs):** `core/.../data/google/GoogleMapsDataSource.kt` (58 KB) implements `MapDataSource`: `search(query, near, span, rankFrom)`, `nearbyPlaces(center, span, onPartial)` (drives ambient layer), `placeDetails(id)`, `reverseGeocode`, `reviews`, `placePhotos`, `directions`, `streetView`. Ranking `ambientProminence(place)` / `rankAmbientPlaces`. Parsers in `core/.../data/google/parse/*` and `SearchParser.kt`, `DirectionsParser.kt`, `PolylineCodec.kt`, `PbBuilder.kt`. Ambient state fed as `ambientPois: List<Place>` from `MapViewModel` → `VelaMapView(ambientPois=…, onAmbientTap=…)`.++**Saved / layers / settings:** saved: `core/.../data/SavedPlaceStore.kt`, `PlaceListStore.kt`, `RecentPlaceStore.kt` + `SavedPlacesSettings.kt`; saved pins layer `SavedPin` in `VelaMapView.kt:240`. Layers toggle: `LayersButton.kt`, `SatelliteLayer.kt`, `TransitLayer.kt`, `Traffic.kt`, `Topography.kt`, `Buildings3d.kt`. Settings: `app/.../ui/settings/*` (`SettingsHub`, `MapSettings`, `NavigationSettings`, `VoiceSettings`, `SearchSettings`, `OfflineSettings`, `AboutSettings`, …).++---++## (b) Existing MA app inventory++**Renderer — CONFIRMED:** MapLibre Native via **`maplibre-compose`** (`org.maplibre.compose.*`, **declarative** Compose layers) over **PMTiles vector tiles** (Protomaps schema). NOT the raster-only `library/map` module.+- Map entry: `ui/MapPage.kt:326` `MaplibreMap(...)`; overlay layer tree `ui/MyMapLayers.kt:47` (`SymbolLayer`/`CircleLayer`/`LineLayer`/`FillLayer`, `GeoJsonSource`/`rememberVectorSource`).+- Base style: asset `maps/src/main/assets/style.json` (v8, 3544 lines) loaded `MapPage.kt:159-169` → `BaseStyle.Json`; source = `pmtiles://https://data.vayunmathur.com/v4.pmtiles`. Runtime online/offline duplication in `patchStyleForHybrid()` `MapPage.kt:545-597` (creates `*_base`/`*_hybrid` layer variants). Disk tile cache `util/MapTileCache.kt`.+- **(a) Hide native POIs:** NO runtime visibility API. Native POI symbol layer is `id:"pois"` (`style.json:2684-2748`, `source-layer:"pois"`); place labels `places_locality`/`places_country`/`places_region`. Suppress by dropping/filtering `pois` in `style.json` and/or in `patchStyleForHybrid`.+- **(b) Custom overlay + tap:** SUPPORTED. Add `GeoJsonSource`+`SymbolLayer` in `MyMapLayers.kt` (existing pattern). Tap hit-test: `onMapClick` `MapPage.kt:335-366` → `camera.projection.queryRenderedFeatures(offset, setOf(...))` → `parse(...)`.+- **Camera:** bearing/tilt/follow already used in nav: `MapPage.kt:281-306` (`bearing = courseOverGround, tilt = 60, zoom = 17`, `autoFollow`, user-pan detect via `camera.isCameraMoving`). Recenter FAB `NavigationOverlay.kt:115-126`.++**amenities.db — to REMOVE (usages):**+- Def/schema/builder: `data/Tag.kt` (`AmenityTag`, `TagDao`, `AmenityEntity`, `AmenityDao.getInBBox` FTS5, `AddressResult`/`AddressDao.search` FTS5 geocoder, `@Database AmenityDatabase`, `buildAmenityDatabase → createFromFile(amenities.db)`). Exported schema `maps/schemas/com.vayunmathur.maps.data.AmenityDatabase/1.json`.+- Repo: `data/AmenityRepository.kt`.+- Download (not bundled): `MainActivity.kt:60` Triple `https://data.vayunmathur.com/amenities.db`.+- Search flow: `util/MapsSearchViewModel.kt` (`getInBBox`, `searchAddresses`, `resolveAmenity`, `SearchResult.Amenity/.Address`); `ui/SearchPage.kt:39,57,63,90`.+- Details flow: `data/SpecificFeature.kt:40-96` (`parse(...)` → `db.tagDao().getTags(id)` for Restaurant/TransitStop/GenericPlace).+- Map tap enrichment: `ui/MapPage.kt:66,69,338-353` (`parse(raw, AmenityRepository.get(context).getDatabase())`).+- Build: `build.gradle.kts:6,42-43` (`ksp` + `implementRoom` — drop only if Room unused elsewhere). Strings: `res/values/strings.xml:110` `downloading_amenity_database`, `:33` `unnamed_amenity`.+- ⚠️ **Removing the DB kills ALL text search AND address geocoding** (`Addresses_fts`). No other geocoder exists → a Google-based search/geocode replacement is REQUIRED (see P3 / Decision D2).++**Routing — KEEP:** on-device **Rust A\*** router `libofflinerouter.so` (`util/OfflineRouter.kt`; rust in `maps/src/main/rust/src/{routing,graph,geometry,mvt,state,lib}.rs`). Outputs full turn-by-turn: `RouteService.Route{duration, distanceMeters, polyline, step[]}`, `Step{…, navInstruction, travelMode, transitDetails, speedRatio}`, maneuver enum `RouteService.kt:16`, icons `ui/ManeuverIcon.kt`. Live nav already exists: `util/NavigationSessionManager.kt` (snap/off-route/arrival/recalc), `util/NavigationService.kt` (foreground svc), `util/NavigationTts.kt` (**system TTS**), `util/PolylineProgress.kt` (ETA/remaining/next-maneuver), `ui/NavigationOverlay.kt` (maneuver card + ETA strip + recenter + arrival). Requests: `util/SelectedFeatureViewModel.kt:89-118`. Rendered: `MyMapLayers.buildRouteFeatures:335-431` → `LineLayer "route"`.++**Current UI:** scaffold `ui/MapPage.kt:308-511` (BottomSheetScaffold + AppScaffold + MaplibreMap); collapsed search bar `:433-440`; full search `ui/SearchPage.kt`; VM/contract `util/MapsSearchViewModel.kt`, `util/MapsUiContract.kt`; bottom sheet `ui/BottomSheetContent.kt` (`RouteSheet:130-242`); place detail `ui/RestaurantBottomSheet.kt`; nav overlay `ui/NavigationOverlay.kt`; downloads `ui/DownloadedMapsPage.kt`.++**Google POI code — KEEP + build on:**+- `data/google/GooglePoiDataSource.kt` — keyless scrape (ported from Vela). `fetch(name, lat, lon): GooglePoiInfo?` (cached LRU 64, 250 m match), `fetchReviews(featureId)`. Endpoints: `search?tbm=map` (`:45`, pb template `:359-378`), reviews RPC (`:47`), session warm (`:49`). `pickEntry`/`parsePlace` already parse `LAT/LNG/NAME/CATEGORY/RATING` per entry (`:167-215`) but **keep only the nearest single match**.+- `data/google/GooglePoiModels.kt` — `GooglePoiInfo{rating, reviewCount, priceText/Level, website, phone, openNow, statusText, category, editorialSummary, featuredReview, hours[], photoUrls[], reviews[], popularTimes, featureId}` (⚠️ **no id / no lat-lng / no name** — caller supplies position). `GoogleReview`, `PoiPopularTimes`.+- `data/google/GoogleResponse.kt` — XSSI strip + positional accessors.+- `ui/PoiEnrichment.kt` — `GooglePoiEnrichment(poi, hasOsmHours)` composable (subtitle/editorial/hours/photos/popular-times/reviews/attribution). Driven by `SelectedFeatureViewModel.currentPoiInfo` (`:68-85`), rendered in `RestaurantBottomSheet.kt`. **Only in the sheet — not on the map.**++---++## (c) Gap analysis (Vela vs MA)++| Area | Vela | MA today | Gap → action |+|---|---|---|---|+| Renderer | MapLibre **imperative** + PMTiles | MapLibre **compose** + PMTiles | Same engine; Vela overlay/nav code is a **pattern port** (translate imperative `addLayer/queryRenderedFeatures` → maplibre-compose declarative layers + `camera.projection`). |+| Native POI suppression | `visibility=NONE` on `poi_r*` at runtime | none (baked style) | Filter/drop `pois` layer in `style.json`/`patchStyleForHybrid`. |+| Amenity source | Google (`GoogleMapsDataSource`) + OSM/Overpass | **amenities.db (OSM)** | Remove DB; make Google-only. |+| POIs on map | ambient Google `SymbolLayer` + dots + tap | **none** (pins come from vector tiles only) | **Build** custom Google-POI overlay + tap→sheet. |+| Search/geocode | Google search + Photon | amenities.db FTS + address FTS | **Replace** with Google search list (generalize `pickEntry`) + Google reverse-geocode. |+| Search-result pins | `MARKERS_LAYER` from search | route/user layers only | Add result-pin layer. |+| Routing | Google directions + on-device fallback | **on-device Rust A\*** (keep) | Reuse MA routing; only borrow UI. |+| Turn-by-turn nav UI | Rich: maneuver banner + **lane guidance** + **road shields** + **speedometer + posted limit** + arrival panel + heading-up compass toggle | Basic maneuver card + ETA strip + recenter + arrival | **Port** the richer nav overlays onto MA's existing nav session. |+| Posted speed limit | maxspeed PMTiles + queryRenderedFeatures | none | Add maxspeed source OR derive from route (Decision D4). |+| Voice | system TTS (+Piper optional) | **system TTS** (`NavigationTts`) | Keep MA's; optionally port voice toggle UI. |+| Place details | `PlaceSheet` (photos/reviews/hours/popular times/directions) | `RestaurantBottomSheet` + `GooglePoiEnrichment` | Port richer layout, keep MA enrichment data. |+| Map layout | search bar + category chips + FAB stack + scale bar + compass + speed widget | search bar + chips + nav overlay | Port layout polish (scale bar, compass toggle, FAB stack, category chips). |+| Saved/layers/settings | full stores + layers button + settings hub | partial | Port incrementally (P6). |++---++## (d) Phased port plan (each phase independently shippable)++### P1 — Amenities → Google-only custom overlay layer+**Goal:** remove `amenities.db`, suppress native basemap POIs, render Google POIs as tappable pins → existing Google details.+**Vela refs:** `VelaMapView.kt` POI-hide `:781-788`; ambient source/layers `:3234-3345`; tap resolution `:1905-1946`; `MapMarker` `:221`; `PoiIcons.kt` (`resultIconKey`, `colorFor`, `vela-poi-<group>`); `GoogleMapsDataSource.nearbyPlaces` (viewport fetch) + `ambientProminence`.+**MA — ADD:**+- `data/google/GooglePoiMapModels.kt` — list-oriented `GooglePoiPin{id, name, lat, lng, category, rating, prominence}` (fills the id/latlng/name gap in `GooglePoiModels.kt`).+- `data/google/GooglePoiDiscovery.kt` — generalize existing `pickEntry`/`parsePlace` (`GooglePoiDataSource.kt:167-215`) to return **List** for a viewport/near query (nearby/search).+- `ui/GooglePoiLayer.kt` — maplibre-compose `GeoJsonSource` + `SymbolLayer` (+ dot layer) for pins, styled from category (port `PoiIcons` grouping to Compose image assets or generated bitmaps).+- POI-pin viewport fetch in a VM (new `util/GooglePoiMapViewModel.kt` or extend `SelectedFeatureViewModel`), keyed on camera idle bbox (reuse `queryVisibleBoundingBox()`).+**MA — CHANGE:**+- `style.json` (`pois` `:2684-2748`) and/or `patchStyleForHybrid` (`MapPage.kt:545-597`): drop/empty-filter the `pois` layer (and `_base`/`_hybrid` variants).+- `MapPage.kt` `onMapClick` `:335-366`: add Google-pin hit-test (query the new pin layer first) → `SelectedFeatureViewModel.set(...)` so `GooglePoiEnrichment` renders; remove the `pois` tile-feature branch + `AmenityRepository.getDatabase()` enrichment (`:66,69,338-353`).+- `MyMapLayers.kt`: mount the new POI-pin layer.+**MA — REMOVE:** `data/Tag.kt`, `data/AmenityRepository.kt`, `schemas/com.vayunmathur.maps.data.AmenityDatabase/`, `MainActivity.kt:60` download, amenity/tag branches in `data/SpecificFeature.kt` + `util/MapsSearchViewModel.kt` (amenity parts) + `ui/SearchPage.kt` (amenity parts), strings `:110,:33`, and `ksp`/`implementRoom` in `build.gradle.kts` **iff** Room unused elsewhere (verify first).+**Reuse:** MA renderer (declarative layers, `queryRenderedFeatures`), existing `GooglePoiDataSource`/`PoiEnrichment`.+**Decisions:** D1 (native POI hide method: edit `style.json` vs runtime filter in `patchStyleForHybrid`); D3 (pin fetch trigger: camera-idle bbox vs fixed radius; caching/quota for scrape); D5 (pin icon rendering: port `PoiIcons` bitmaps vs Compose `SymbolLayer` images). **Note:** address geocoding also dies here — either ship P1 with search still on the DB (remove DB only after P3) or sequence P3 before fully deleting `AddressDao`. Recommend: P1 removes amenity **map/details** paths + suppresses POIs + adds overlay, but keep DB search until P3, then delete.++### P2 — Map-screen layout to match Vela+**Goal:** match Vela's browse layout/polish.+**Vela refs:** `MapScreen.kt` (`MapScreen`, `CategoryChips`, `SearchEntryContent`, `ScaleBarReader`), `ScaleBar.kt`, `LayersButton.kt`, compass toggle (`onCompassTap`), FAB stack.+**MA — ADD:** `ui/MapScaleBar.kt`, `ui/CompassButton.kt` (heading-up/north-up toggle bound to `CameraState.bearing`), `ui/CategoryChips.kt`, `ui/LayersButton.kt`.+**MA — CHANGE:** `MapPage.kt:308-511` scaffold — arrange search bar + chips + FAB stack (locate/layers/compass) + scale bar per Vela; use `library/ui` scaffold (avoid `RawScaffoldInApp`).+**Reuse:** renderer camera (`MapPage.kt:281-306`).+**Decisions:** D6 (which controls surface on browse vs nav; FAB order).++### P3 — Search UX (Google-only)+**Goal:** replace DB search/geocode with Google; Vela search look.+**Vela refs:** `SearchBar.kt`, `MapScreen.SearchResults`/`CategoryChips`, `GoogleMapsDataSource.search`/`reverseGeocode`, `RecentSearchStore.kt`, `CategoryFilter.kt`.+**MA — ADD:** `data/google/GoogleSearchDataSource.kt` (search list + reverse-geocode via generalized discovery), `data/RecentSearchStore.kt`.+**MA — CHANGE:** `util/MapsSearchViewModel.kt` + `util/MapsUiContract.kt` (results from Google, drop `SearchResult.Amenity/.Address`), `ui/SearchPage.kt` (Vela-style results/chips, remove `AmenityRepository`).+**MA — REMOVE (final):** the remaining `amenities.db` search/geocode paths + `AddressDao`/`AmenityDao` (completes P1's deferred deletion).+**Reuse:** existing scrape/parse infra.+**Decisions:** D2 (geocode replacement: Google reverse-geocode scrape reliability/quota; offline-search story — DB removal drops offline search, confirm acceptable), D7 (debounce/session tokens for scrape).++### P4 — Place-details sheet layout+**Goal:** Vela `PlaceSheet` layout, MA data.+**Vela refs:** `PlaceSheet.kt` (`PlaceSheet`, `DirectionsPanel`, `RouteOption`, photo gallery, reviews, popular times), `RatingStars.kt`, `RouteTopCard.kt`.+**MA — ADD/CHANGE:** rework `ui/RestaurantBottomSheet.kt` → `ui/PlaceSheet.kt` layout; keep `GooglePoiEnrichment` (`PoiEnrichment.kt`) + `currentPoiInfo` as the data source; wire "Directions" to MA routing (`SelectedFeatureViewModel.routes`).+**Reuse:** `GooglePoiInfo`, MA routing, `BottomSheetContent.RouteSheet`.+**Decisions:** D8 (which Google fields are reliably scraped for the header/gallery).++### P5 — Driving / turn-by-turn nav UI (MA routing + system TTS)+**Goal:** upgrade MA's nav overlay to Vela's richness on top of MA's existing nav session.+**Vela refs:** `NavOverlays.kt` (`ManeuverBanner`, `LaneGuide`/`LaneDiagram`, `SignChip`/`roadSigns`, `NavControls`, `ArrivalSummary`), `RouteShield.kt`, `StepsSheet.kt`, `MapScreen.SpeedWidget`, `Format.formatSpeedLimit`, compass heading-up toggle.+**MA — ADD:** `ui/nav/ManeuverBanner.kt`, `ui/nav/LaneGuidance.kt`, `ui/nav/RouteShield.kt`, `ui/nav/StepsSheet.kt`, `ui/nav/SpeedWidget.kt` (speedometer + posted-limit badge), `ui/nav/ArrivalSummary.kt`.+**MA — CHANGE:** `ui/NavigationOverlay.kt` compose the new banners; `MapPage.kt` nav camera already heading-up/tilt (`:281-306`) — add compass north-up toggle + re-center override reset (port Vela's `navRecenterTick` idea). Feed from `PolylineProgress` (`distanceToNextManeuver`, `etaEpochMs`) + `RouteService.Step.navInstruction`/maneuver enum + `speedRatio`.+**MA — REUSE (do not port):** `NavigationSessionManager`, `NavigationService`, `NavigationTts` (system TTS), Rust routing, `PolylineProgress`, `ManeuverIcon`.+**Skip from Vela:** Piper/`NeuralSynth`/`PiperCatalog`/`VelaPiper`/`VoiceLibrary`.+**Decisions:** D4 (posted speed limit source: add a maxspeed PMTiles overlay + `queryRenderedFeatures` like Vela `:967-1003`, vs derive from route `speedRatio`/graph, vs omit); D9 (lane-guidance data: Rust router currently has no lane info → either extend graph output or hide `LaneDiagram` until available); D10 (road-shield data: derive from `roadName`/ref parsing).++### P6 — Saved places, layers toggle, settings + remaining features+**Goal:** feature parity extras.+**Vela refs:** `SavedPlaceStore.kt`, `PlaceListStore.kt`, `RecentPlaceStore.kt`, `SavedPlacesSettings.kt`, saved-pin layer (`SavedPin`); `LayersButton.kt` + `SatelliteLayer`/`TransitLayer`/`Traffic`/`Topography`/`Buildings3d`; `settings/*` hub.+**MA — ADD:** `data/SavedPlaceStore.kt` + saved-pin overlay layer; `ui/LayersSheet.kt` (satellite/traffic/transit toggles — MA already has `traffic-layer` in `MyMapLayers.kt:122-137`); `ui/settings/MapSettings.kt` etc. as needed.+**MA — CHANGE:** mount saved-pin layer in `MyMapLayers.kt`; add saved-pin tap → sheet in `onMapClick`.+**Reuse:** existing traffic layer + renderer.+**Decisions:** D11 (satellite/transit tile sources & keys); D12 (settings scope for v1).++### P7 — Google Street View (keyless, reuse photos app renderer)+**Goal:** add Street View panorama viewing. RENDERER DECISION (user): do NOT port Vela's bespoke GLES 2.0 sphere — instead REUSE the photos app's existing image viewer/renderer to display the equirectangular pano (pan/zoom), which is simpler and consistent with the suite. The P7 agent must locate the photos app's image-viewer component (photos/src/main/java/... the zoom/pan image display used in its editor/gallery) and reuse it for the pano image.+**Vela refs (data only, NOT the renderer):** `core/.../data/google/StreetViewParser.kt` (keyless pano metadata: panoId, lat/lng, links/neighbors, date, heading), `StreetViewTiles.kt` (equirect tile fetch/stitch by zoom), `GoogleMapsDataSource.streetView`. Skip Vela's `PanoramaView.kt` (GLES sphere) — replaced by the photos renderer.+**MA — ADD:** `data/google/StreetViewDataSource.kt` (port StreetViewParser + equirect tile fetch/stitch via :library:network — keyless pano metadata + tiles → one equirect bitmap), `ui/streetview/StreetViewScreen.kt` (full-screen viewer using the PHOTOS APP's image renderer/viewer to pan/zoom the equirect bitmap; shared library/ui scaffold; move between adjacent panos via links).+**MA — CHANGE:** Street View entry points — from the place-details sheet (P4 `PlaceSheet`) when a pano exists, and optionally a long-press-on-map "Street View here"; nearest-pano lookup by lat/lng.+**Reuse:** the photos app image viewer (renderer), existing Google scrape infra, library/ui, library/image.+**Decisions:** D13 (tile zoom/quality vs bandwidth; caching), D14 (entry points: place sheet only vs also map long-press). Threading: all tile/metadata fetch on Dispatchers.IO.++---++## Suggested sequencing++## Cross-cutting decisions (need answers before coding)+- **D1** Native-POI hide: static `style.json` edit vs runtime filter in `patchStyleForHybrid`. (Recommend runtime, so it stays OTA-swappable.)+- **D2** Geocoding after DB removal: Google reverse-geocode scrape only? Accept loss of **offline** search/geocode?+- **D3/D7** Scrape quota/caching/debounce for viewport POI fetch + search (keyless scrape rate limits).+- **D4** Posted speed limit source (maxspeed PMTiles overlay vs route-derived vs omit).+- **D5** POI pin icon rendering (port `PoiIcons` bitmap factory vs Compose `SymbolLayer` images).+- **D9/D10** Lane guidance + road shields need data the Rust router may not emit — extend router output or ship UI degraded.+- **D-arch** Port Vela's imperative MapLibre overlay code as **maplibre-compose declarative** layers (recommended, matches MA) vs reach through to raw `MapLibreMap`.++## Suggested sequencing+P1 (map/details Google-only + suppress POIs, keep DB search) → P3 (Google search, then delete DB) → P2 (layout) → P4 (details) → P7 (street view, entry from the place sheet) → P5 (nav UI) → P6 (extras). P1 and P3 are the critical path (they own DB removal); P2/P4/P7/P5/P6 are largely independent afterward.++---++## CONFIRMED DECISIONS (user sign-off)+- **D2 / offline search:** ACCEPT online-only (Google) search. Removing `amenities.db` intentionally drops offline search + geocoding; no offline fallback. All search + reverse-geocode = Google scrape.+- **D4 / posted speed limit:** ADD a real maxspeed data source (maxspeed PMTiles overlay + `queryRenderedFeatures` under the puck, like Vela `VelaMapView.kt:967-1003` + `OsmMaxspeed.kt`). The driving UI shows accurate posted limits (P5).+- **D9 / lane guidance:** EXTEND the Rust router (`maps/src/main/rust/`) to emit lane info so Vela's lane diagrams work (P5; can be prepped early since it's isolated from the UI phases).+- **Defaults applied (no further input needed):** D1 runtime POI-hide (filter in `patchStyleForHybrid`, OTA-swappable); D-arch port as maplibre-compose **declarative** layers; D3/D7 debounced + LRU-cached viewport scrape; D5 pin icons as Compose `SymbolLayer` images/generated bitmaps; D10 road shields derived from road name/ref.
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 44a24a38a9..118f5ca883 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -24,6 +24,7 @@ import com.vayunmathur.maps.util.MapsSearchViewModel import com.vayunmathur.maps.util.MapsZonesViewModel import com.vayunmathur.maps.util.SavedPlacesViewModel import com.vayunmathur.maps.util.SelectedFeatureViewModel+import com.vayunmathur.maps.util.GooglePoiMapViewModel import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle import kotlinx.serialization.Serializable@@ -107,11 +108,12 @@ fun Navigation( searchViewModel: MapsSearchViewModel = viewModel(), zonesViewModel: MapsZonesViewModel = viewModel(), savedPlacesViewModel: SavedPlacesViewModel = viewModel(),+ poiViewModel: GooglePoiMapViewModel = viewModel(), ) { val backStack = rememberNavBackStack<Route>(Route.MapPage) MainNavigation(backStack) { entry<Route.MapPage> {- MapPage(backStack, viewModel, zonesViewModel, savedPlacesViewModel)+ MapPage(backStack, viewModel, zonesViewModel, savedPlacesViewModel, poiViewModel) } entry<Route.DownloadedMapsPage> { DownloadedMapsPage(backStack, zonesViewModel)
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 4ff82bdbef..5cce031163 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt@@ -7,7 +7,6 @@ import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonPrimitive import org.maplibre.spatialk.geojson.Feature import org.maplibre.spatialk.geojson.Geometry-import org.maplibre.spatialk.geojson.Point import org.maplibre.spatialk.geojson.Position @Serializable@@ -37,13 +36,15 @@ typealias Feature1 = Feature<Geometry, JsonObject?> fun JsonObject.string(key: String): String? = this[key]?.jsonPrimitive?.content -suspend fun parse(feature: Feature1, repository: com.vayunmathur.maps.data.AmenityRepository): SpecificFeature? {- return parse(feature, repository.getDatabase())-}--suspend fun parse(feature: Feature1, db: AmenityDatabase): SpecificFeature? {- val id = feature.id?.jsonPrimitive?.content?.toULong() ?: 0uL- val geometry = feature.geometry+/**+ * Resolve a tapped basemap feature into a [SpecificFeature].+ *+ * Amenities are now Google-only (rendered on the custom overlay layer and tapped+ * there — see GooglePoiLayer), so this no longer reads the amenities DB: it only+ * handles the country/region admin labels (Wikidata-backed). Everything else+ * returns null, since native POIs are suppressed in the style.+ */+suspend fun parse(feature: Feature1): SpecificFeature? { val properties = feature.properties ?: return null return when(properties.string("kind")) { "country" -> {@@ -65,37 +66,6 @@ suspend fun parse(feature: Feature1, db: AmenityDatabase): SpecificFeature? { val name = properties.string("name:en") ?: properties.string("name") ?: return null SpecificFeature.Admin1Label(iso, wikipediaUrl, name) }- "restaurant", "fast_food", "cafe", "bar" -> {- val point = geometry as? Point ?: return null- val tags = db.tagDao().getTags(id.toLong()).associate { it.key to it.value }- SpecificFeature.Restaurant(tags["name"] ?: "", tags["phone"], tags["website"], tags["website:menu"], tags["opening_hours"]?.let { OpeningHours.from(it) }, point.coordinates)- }- "bus_stop", "bus_station", "tram_stop", "railway_station", "subway_entrance" -> {- val point = geometry as? Point ?: return null- val tags = db.tagDao().getTags(id.toLong()).associate { it.key to it.value }- val gtfsTag = tags.keys.find { it.startsWith("gtfs:stop_code:") }- val gtfsFeed = gtfsTag?.removePrefix("gtfs:stop_code:")- val stopCode = gtfsTag?.let { tags[it] }- SpecificFeature.TransitStop(tags["name"] ?: "", stopCode, gtfsFeed, point.coordinates)- }- !in listOf(- "country", "region", "county", "locality", "address", "building", "building_part",- "barren", "farmland", "forest", "glacier", "grassland", "scrub", "urban_area",- "earth", "aerodrome", "attraction", "bare_rock", "beach", "cafe", "camp_site",- "cemetery", "college", "commercial", "dog_park", "farmyard", "footway", "garden",- "golf_course", "grass", "grocery", "hospital", "hotel", "industrial", "kindergarten",- "library", "marina", "meadow", "military", "national_park", "nature_reserve",- "neighbourhood", "orchard", "other", "park", "pedestrian", "pier", "pitch",- "platform", "playground", "post_office", "protected_area", "railway", "runway",- "recreation_ground", "residential", "sand", "school", "stadium", "supermarket",- "taxiway", "townhall", "university", "wetland", "wood", "zoo", "macrohood",- "highway", "major_road", "minor_road", "path", "aerialway", "ferry", "rail",- "aeroway", "water", "lake", "playa", "ocean"- ) -> {- val point = geometry as? Point ?: return null- val tags = db.tagDao().getTags(id.toLong()).associate { it.key to it.value }- SpecificFeature.GenericPlace(tags["name"] ?: "", tags["phone"], tags["website"], tags["opening_hours"]?.let { OpeningHours.from(it) }, point.coordinates)- } else -> null } }\ No newline at end of file
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.ktnew file mode 100644index 0000000000..552f35000f--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDiscovery.kt@@ -0,0 +1,189 @@+package com.vayunmathur.maps.data.google++import com.vayunmathur.library.network.NetworkClient+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlinx.serialization.json.JsonElement+import java.net.URLEncoder+import kotlin.math.ln++/**+ * 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.+ *+ * 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].+ *+ * Debounced + LRU-cached (D3/D7): the ViewModel debounces the camera-idle+ * trigger, and results are cached here per viewport centre rounded to ~100 m so+ * a small pan back into a visited area doesn't refetch.+ *+ * 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 {++ // 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/",+ )++ /** Broad default so a viewport comes back populated with mixed POIs rather+ * than filtered to a single business type. */+ private const val DEFAULT_QUERY = "points of interest"++ /** Cap pins per fetch so a dense downtown viewport doesn't push hundreds of+ * symbols onto the map (kept by descending [GooglePoiPin.prominence]). */+ private const val MAX_PINS = 60++ @Volatile private var sessionWarmed = false++ // Bounded access-ordered LRU keyed on rounded centre + query. Guarded by+ // synchronized(cache).+ private data class Key(val lat: Double, val lon: Double, val query: String)+ 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]. Never throws — returns an empty list when+ * the scrape fails or the positional paths drift. LRU-cached on the centre+ * rounded to ~100 m so re-visiting an area is instant.+ */+ suspend fun nearby(lat: Double, lon: Double, query: String = DEFAULT_QUERY): List<GooglePoiPin> {+ val key = Key(round3(lat), round3(lon), query)+ synchronized(cache) { cache[key]?.let { return it } }+ val pins = runCatching { fetch(lat, lon, query) }.getOrDefault(emptyList())+ synchronized(cache) { cache[key] = pins }+ return pins+ }++ private suspend fun fetch(lat: Double, lon: Double, query: String): List<GooglePoiPin> =+ withContext(Dispatchers.IO) {+ warmSession()+ val pb = buildViewportPb(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()+ 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; the rest are de-duped by feature id and+ * ranked by [prominenceOf] before the [MAX_PINS] cap.+ */+ 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),+ )+ }+ .distinctBy { it.id }+ .sortedByDescending { it.prominence }+ .take(MAX_PINS)+ }++ /** Cheap stand-in for Vela's `ambientProminence`: rating weighted by the log+ * of the review count, so a well-reviewed 4.5 outranks a lone 5.0. */+ private fun prominenceOf(rating: Double?, reviews: Int): Double {+ val r = rating ?: return 0.0+ return r * (1.0 + ln(1.0 + reviews.coerceAtLeast(0)))+ }++ // --- 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+ }++ private fun buildViewportPb(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 round3(v: Double): Double = Math.round(v * 1000.0) / 1000.0+ private fun String.enc(): String = URLEncoder.encode(this, "UTF-8")++ // Same calibrated pb template as GooglePoiDataSource — the `!2d<lng>!3d<lat>`+ // block centres the viewport 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/GooglePoiMapModels.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiMapModels.kt b/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiMapModels.ktnew file mode 100644index 0000000000..3271a1e61f--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiMapModels.kt@@ -0,0 +1,21 @@+package com.vayunmathur.maps.data.google++/**+ * List-oriented model for the custom Google POI overlay layer.+ *+ * [GooglePoiInfo] (the bottom-sheet enrichment) deliberately carries no id, no+ * lat/lng and no name — the caller already knew the place and supplied its+ * position. Map pins are the opposite: we discover many places from a viewport+ * scrape and must be able to draw each one and, on tap, re-select it. So this+ * fills that gap with the minimum a pin needs: a stable id, a name, a position,+ * plus category/rating for styling and [prominence] for ranking/limiting.+ */+data class GooglePoiPin(+ val id: String,+ val name: String,+ val lat: Double,+ val lng: Double,+ val category: String? = null,+ val rating: Double? = null,+ val prominence: Double = 0.0,+)
maps/src/main/java/com/vayunmathur/maps/ui/GooglePoiLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/GooglePoiLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/GooglePoiLayer.ktnew file mode 100644index 0000000000..075e37e5d2--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/GooglePoiLayer.kt@@ -0,0 +1,170 @@+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.google.GooglePoiPin+import com.vayunmathur.maps.data.string+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.convertToColor+import org.maplibre.compose.expressions.dsl.feature+import org.maplibre.compose.expressions.dsl.image+import org.maplibre.compose.expressions.dsl.interpolate+import org.maplibre.compose.expressions.dsl.linear+import org.maplibre.compose.expressions.dsl.zoom+import org.maplibre.compose.expressions.value.StringValue+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 first in MapPage.onMapClick so a Google pin tap+ * wins over basemap label features. */+const val GOOGLE_POI_LAYER_ID = "google-poi-pins"+private const val GOOGLE_POI_DOT_LAYER_ID = "google-poi-dots"+private const val GOOGLE_POI_SOURCE_ID = "google-poi-geojson"++/**+ * Custom Google-POI overlay: a [GeoJsonSource] fed from the viewport scrape plus+ * a category-coloured [CircleLayer] "dot" and a [SymbolLayer] marker on top+ * (Vela's ambient dot + icon pattern, ported to maplibre-compose declarative+ * layers). Native basemap POIs are suppressed (see MapPage.patchStyleForHybrid),+ * so these are the only POI pins on the map.+ *+ * Icons are Compose-generated bitmaps (Decision D5): the marker glyph is drawn+ * once with a [android.graphics.Canvas]; per-place colour is data-driven from+ * each feature's `color` property (derived from its category).+ */+@Composable+@MaplibreComposable+fun GooglePoiLayer(pins: List<GooglePoiPin>) {+ val marker = remember { generateMarkerBitmap() }+ var source by remember { mutableStateOf<GeoJsonSource?>(null) }++ LaunchedEffect(Unit) {+ source = GeoJsonSource(+ GOOGLE_POI_SOURCE_ID,+ GeoJsonData.Features(FeatureCollection(emptyList<Feature1>())),+ GeoJsonOptions(),+ )+ }++ source?.let { src ->+ LaunchedEffect(pins) {+ src.setData(GeoJsonData.Features(FeatureCollection(pins.map { it.toFeature() })))+ }++ // Category-coloured base dot (the pin body).+ CircleLayer(+ GOOGLE_POI_DOT_LAYER_ID,+ src,+ color = feature["color"].cast<StringValue>().convertToColor(),+ radius = interpolate(+ linear(), zoom(),+ 11 to const(4.dp),+ 14 to const(6.dp),+ 17 to const(8.dp),+ ),+ strokeColor = const(Color.White),+ strokeWidth = const(1.5.dp),+ )++ // White centre glyph (generated bitmap) so the pin reads as a marker.+ SymbolLayer(+ GOOGLE_POI_LAYER_ID,+ src,+ iconImage = image(marker),+ iconSize = interpolate(+ linear(), zoom(),+ 11 to const(0.35f),+ 14 to const(0.5f),+ 17 to const(0.65f),+ ),+ )+ }+}++/** Rebuild a pin as a GeoJSON point feature; category → display colour is baked+ * into `color` so the CircleLayer can style it data-driven, and name/lat/lng+ * ride along so onMapClick can re-select the place. */+private fun GooglePoiPin.toFeature(): Feature1 = Feature1(+ Point(Position(lng, lat)),+ JsonObject(+ mapOf(+ "id" to JsonPrimitive(id),+ "name" to JsonPrimitive(name),+ "lat" to JsonPrimitive(lat),+ "lng" to JsonPrimitive(lng),+ "category" to JsonPrimitive(category ?: ""),+ "color" to JsonPrimitive(colorForCategory(category)),+ )+ ),+)++/**+ * Convert a hit-tested pin feature back into a selectable place. We reuse+ * [SpecificFeature.GenericPlace] (name + position) so the existing+ * `SelectedFeatureViewModel.currentPoiInfo` flow fetches the Google enrichment+ * and `GooglePoiEnrichment` renders in the sheet — no new detail path needed.+ */+fun Feature1.toSelectedGooglePoi(): 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))+}++/** Category → pin colour, mirroring Vela's `PoiIcons.colorFor(group)` grouping. */+private fun colorForCategory(category: String?): String {+ val c = category?.lowercase() ?: return "#EA4335"+ return when {+ listOf("restaurant", "food", "dining", "pizza", "burger", "steak", "sushi").any { it in c } -> "#EA4335"+ listOf("cafe", "coffee", "bakery", "tea", "dessert").any { it in c } -> "#F9AB00"+ listOf("bar", "pub", "night", "brew", "wine").any { it in c } -> "#A142F4"+ listOf("hotel", "lodging", "motel", "hostel", "resort").any { it in c } -> "#4285F4"+ listOf("store", "shop", "market", "mall", "grocery", "supermarket").any { it in c } -> "#1A73E8"+ listOf("gas", "fuel", "charging", "ev ").any { it in c } -> "#34A853"+ listOf("park", "garden", "trail", "recreation", "museum", "gallery").any { it in c } -> "#34A853"+ listOf("hospital", "clinic", "pharmacy", "doctor", "health", "dentist").any { it in c } -> "#D93025"+ listOf("bank", "atm", "finance").any { it in c } -> "#188038"+ listOf("school", "university", "college", "library").any { it in c } -> "#F29900"+ else -> "#5F6368"+ }+}++/** Draw the marker once: a white-ringed dot used as the SymbolLayer glyph on top+ * of the category-coloured base circle. */+private fun generateMarkerBitmap(): 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 / 2f - 4f, paint)+ paint.color = android.graphics.Color.parseColor("#33000000")+ paint.style = android.graphics.Paint.Style.STROKE+ paint.strokeWidth = 3f+ canvas.drawCircle(cx, cy, size / 2f - 5f, paint)+ return bmp.asImageBitmap()+}
maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.ktindex fe5c8fa5d3..4a95c322ba 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -63,7 +63,6 @@ import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.ui.IconWork import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.maps.Route-import com.vayunmathur.maps.data.AmenityRepository import com.vayunmathur.maps.data.SavedPlace import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.data.parse@@ -72,6 +71,7 @@ import com.vayunmathur.maps.util.MapsZonesViewModel 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.SelectedFeatureViewModel import com.vayunmathur.maps.util.ZoneDownloadManager import kotlinx.coroutines.Dispatchers@@ -105,7 +105,7 @@ import com.vayunmathur.maps.R as MapsR @OptIn(ExperimentalMaterial3Api::class) @Composable-fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, zonesViewModel: MapsZonesViewModel, savedPlacesViewModel: SavedPlacesViewModel) {+fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, zonesViewModel: MapsZonesViewModel, savedPlacesViewModel: SavedPlacesViewModel, poiViewModel: GooglePoiMapViewModel) { val selectedFeature by viewModel.selectedFeature.collectAsState() val context = LocalContext.current val coroutineScope = rememberCoroutineScope()@@ -113,6 +113,10 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, val savedHome by savedPlacesViewModel.home.collectAsState() val savedWork by savedPlacesViewModel.work.collectAsState() + // Google POI overlay pins (viewport scrape → custom layer, replacing the+ // suppressed native basemap POIs).+ val googlePins by poiViewModel.pins.collectAsState()+ // --- ZONE DOWNLOAD STATE --- val camera = rememberCameraState(CameraPosition(target = Position(-118.243683,34.052235), zoom = 5.0)) @@ -135,6 +139,9 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, OfflineRouter.ensureTrafficLoadedNative(bbox.north, bbox.west, true) OfflineRouter.ensureTrafficLoadedNative(bbox.south, bbox.east, true) OfflineRouter.ensureTrafficLoadedNative(bbox.south, bbox.west, true)+ // Refresh the Google POI overlay for the idle viewport (VM+ // debounces + LRU-caches the keyless scrape).+ poiViewModel.onViewport(bbox.north, bbox.east, bbox.south, bbox.west) } } }@@ -335,22 +342,40 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, onMapClick = { _, 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+ // SelectedFeatureViewModel.currentPoiInfo fetches+ // the enrichment and GooglePoiEnrichment renders.+ val poiHit = projection?.queryRenderedFeatures(+ offset,+ setOf(GOOGLE_POI_LAYER_ID)+ )?.firstNotNullOfOrNull { it.toSelectedGooglePoi() }+ if (poiHit != null) {+ if (selectedFeature is SpecificFeature.Route) viewModel.setInactiveNavigation(+ selectedFeature as SpecificFeature.Route+ )+ viewModel.set(poiHit)+ scaffoldState.bottomSheetState.expand()+ return@launch+ }++ // Otherwise fall back to basemap admin labels+ // (country/region). Native POIs are suppressed+ // and the amenity-DB enrichment path is gone. val features = projection?.queryRenderedFeatures( offset,- setOf("places_country", "places_region", "pois").flatMap {+ setOf("places_country", "places_region").flatMap { listOf("${it}_base", "${it}_hybrid") }.toSet() ) ?: emptyList()- // parse() may do network (Wikidata) + Room- // per feature. queryRenderedFeatures returns- // one Feature PER LAYER at the tap point —- // often 2-3 — and we only use the first- // parseable result. Stop at the first hit- // instead of doing every Wikidata round-trip- // serially in the foreground.+ // parse() may do a Wikidata round-trip per+ // feature; queryRenderedFeatures returns one+ // Feature PER LAYER at the tap point, so stop at+ // the first parseable hit instead of doing every+ // round-trip serially in the foreground. val firstFeature = withContext(Dispatchers.IO) { features.firstNotNullOfOrNull { raw ->- runCatching { parse(raw, AmenityRepository.get(context).getDatabase()) }.getOrNull()+ runCatching { parse(raw) }.getOrNull() } } @@ -365,7 +390,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, ClickResult.Pass } ) {- MyMapLayers(selectedFeature, route?.get(selectedRouteType), json, userPosition, userBearing, navProgress)+ MyMapLayers(selectedFeature, route?.get(selectedRouteType), json, userPosition, userBearing, navProgress, googlePins) } } @@ -542,6 +567,11 @@ fun calculateZoneId(lat: Double, lon: Double, zoom: Float): Int? { return ((spatialId ushr 58) and 0x3F).toInt() } +// Native basemap layers suppressed at runtime — amenities are Google-only now+// (custom overlay layer). Keeping this in code (vs editing style.json) makes it+// OTA-swappable per Decision D1.+private val SUPPRESSED_LAYERS = setOf("pois")+ fun patchStyleForHybrid( jsonString: String, baseLocalUrl: String,@@ -568,6 +598,12 @@ fun patchStyleForHybrid( val id = layer["id"]?.jsonPrimitive?.content ?: "" val type = layer["type"]?.jsonPrimitive?.content ?: "" + // Suppress native basemap POIs at runtime (Decision D1) — amenities+ // are Google-only now, rendered on the custom overlay layer. Dropping+ // the source layer here (rather than editing style.json) keeps it+ // OTA-swappable. Also drops the would-be _base/_hybrid variants.+ if (id in SUPPRESSED_LAYERS) return@forEach+ if (type == "background") { add(layer) } else {
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 a22f07b6f2..fc66e73d80 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt@@ -14,6 +14,7 @@ import androidx.compose.ui.unit.dp import com.vayunmathur.maps.data.CountryMap import com.vayunmathur.maps.data.Feature1 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 kotlinx.serialization.json.JsonObject@@ -51,6 +52,7 @@ fun MyMapLayers( userPosition: Position, userBearing: Float, navProgress: com.vayunmathur.maps.util.NavigationProgress? = null,+ googlePins: List<GooglePoiPin> = emptyList(), ) { val trafficVersion by OfflineRouter.trafficVersion.collectAsState() val context = LocalContext.current@@ -136,6 +138,10 @@ fun MyMapLayers( cap = const(LineCap.Butt) ) + // Custom Google POI overlay (replaces suppressed native basemap POIs).+ // Rendered above traffic but below the user puck.+ GooglePoiLayer(googlePins)+ userSource?.let { src -> LaunchedEffect(userPosition, userBearing) { src.setData(
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.ktnew file mode 100644index 0000000000..7fe997342e--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/GooglePoiMapViewModel.kt@@ -0,0 +1,67 @@+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.FlowPreview+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.debounce+import kotlinx.coroutines.flow.distinctUntilChanged+import kotlinx.coroutines.flow.filterNotNull+import kotlinx.coroutines.flow.flowOn+import kotlinx.coroutines.flow.mapLatest+import kotlinx.coroutines.flow.stateIn+import kotlin.math.abs++/**+ * Drives the custom Google-POI overlay: turns camera-idle viewport boxes into a+ * debounced, LRU-cached list of [GooglePoiPin]s to render (Decisions D3/D7).+ *+ * [onViewport] is fed from `MapPage`'s camera effect (which already computes the+ * visible bbox via `queryVisibleBoundingBox()`); the centre is rounded and the+ * trigger debounced so panning doesn't hammer the keyless scrape, and+ * [GooglePoiDiscovery] caches per centre so a pan-back is instant. Only+ * sufficiently zoomed-in views fetch — a continent-wide box is skipped (POI pins+ * are meaningless there and it'd be pure quota). All network is on+ * [Dispatchers.IO].+ */+class GooglePoiMapViewModel(application: Application) : AndroidViewModel(application) {++ // Rounded viewport centre (lat, lon); null suppresses fetching (zoomed out).+ private val _center = MutableStateFlow<Pair<Double, Double>?>(null)++ @OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)+ val pins: StateFlow<List<GooglePoiPin>> = _center+ .filterNotNull()+ .debounce(DEBOUNCE_MS)+ .distinctUntilChanged()+ .mapLatest { (lat, lon) -> GooglePoiDiscovery.nearby(lat, lon) }+ .flowOn(Dispatchers.IO)+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())++ /**+ * Feed a camera-idle viewport (from `queryVisibleBoundingBox()`). Views wider+ * than [MAX_LAT_SPAN] clear the pins instead of fetching; otherwise the box+ * centre (rounded by [GooglePoiDiscovery]) becomes the next fetch key.+ */+ fun onViewport(north: Double, east: Double, south: Double, west: Double) {+ if (abs(north - south) > MAX_LAT_SPAN) {+ _center.value = null+ return+ }+ _center.value = ((north + south) / 2.0) to ((east + west) / 2.0)+ }++ private companion object {+ const val DEBOUNCE_MS = 600L++ // ~16 km of latitude — roughly city-zoom; wider views skip the scrape.+ const val MAX_LAT_SPAN = 0.15+ }+}