maps P7: Google Street View (keyless) via photos-style pan/zoom renderer
- Commit
fdc79a3031794d1fa6e87b0359aba5afaed6922e- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-16 23:04 UTC (3 months ago)
- Parents
e8f7de2
Diff
maps/src/main/java/com/vayunmathur/maps/data/google/StreetViewDataSource.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/google/StreetViewDataSource.kt b/maps/src/main/java/com/vayunmathur/maps/data/google/StreetViewDataSource.ktnew file mode 100644index 0000000000..f5b1a831e3--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/data/google/StreetViewDataSource.kt@@ -0,0 +1,328 @@+package com.vayunmathur.maps.data.google++import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.graphics.Canvas+import android.graphics.Rect+import com.vayunmathur.library.network.NetworkClient+import kotlinx.coroutines.Deferred+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.withContext+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonElement+import kotlin.math.abs+import kotlin.math.atan2+import kotlin.math.cos+import kotlin.math.sin+import kotlin.math.sqrt++/**+ * Keyless Google Street View.+ *+ * Ported from Vela (data layer only): the device calls the same undocumented+ * endpoints a logged-out browser / the JS Maps API does — no API key, authorised+ * by a browser-like `User-Agent` + `Referer`. Two metadata endpoints feed one+ * parser (both return a deeply nested *positional* JSON array, no field names):+ * - `GeoPhotoService.SingleImageSearch` — nearest pano to a lat/lng (a `cb(…)`+ * callback wrapper);+ * - `photometa/v1` — a pano by id, used to walk to a neighbour (a `)]}'` guard).+ * Tiles come from `streetviewpixels-pa.googleapis.com/v1/tile` (keyless JPEG).+ *+ * RENDERER NOTE: unlike Vela (a GLES sphere) this returns a single stitched+ * *equirectangular* [Bitmap]; the viewer ([ui.streetview.StreetViewScreen]) shows+ * it with the photos-app pan/zoom image renderer.+ *+ * All network runs on [Dispatchers.IO]; every accessor is null-safe so a Google+ * reshape degrades to "no imagery" instead of throwing. Pano metadata is cached in+ * a small bounded LRU. Bitmaps are NOT cached here (they're large and owned by the+ * viewer for its current pano).+ *+ * NOTE (on-device): the live fetch + tile stitch needs a device with network — it+ * can't be exercised at compile time.+ */+object StreetViewDataSource {++ // Nearest-pano lookup (SingleImageSearch). {LAT}/{LNG} = the query point;+ // `!2d50` is the search radius in metres. `&callback=cb` → a JS callback body.+ private const val META_URL =+ "https://maps.googleapis.com/maps/api/js/GeoPhotoService.SingleImageSearch?pb=" ++ "!1m5!1sapiv3!5sUS!11m2!1m1!1b0!2m4!1m2!3d{LAT}!4d{LNG}!2d50!3m10!2m2!1sen!2sUS" ++ "!9m1!1e2!11m4!1m3!1e2!2b1!3e2!4m10!1e1!1e2!1e3!1e4!1e8!1e6!5m1!1e2!6m1!1e2&callback=cb"++ // By-pano-id metadata (photometa/v1). `!3m3!1m2!1e2!2s{PANOID}` selects the pano.+ private const val PANO_URL =+ "https://www.google.com/maps/photometa/v1?authuser=0&hl=en&gl=us&pb=" ++ "!1m4!1smaps_sv.tactile!11m2!2m1!1b1!2m2!1sen!2sus!3m3!1m2!1e2!2s{PANOID}" ++ "!4m57!1e1!1e2!1e3!1e4!1e5!1e6!1e8!1e12!2m1!1e1!4m1!1i48!5m1!1e1!5m1!1e2!6m1!1e1!6m1!1e2" ++ "!9m36!1m3!1e2!2b1!3e2!1m3!1e2!2b0!3e3!1m3!1e3!2b1!3e2!1m3!1e3!2b0!3e3!1m3!1e8!2b0!3e3" ++ "!1m3!1e1!2b0!3e3!1m3!1e4!2b0!3e3!1m3!1e10!2b1!3e2!1m3!1e10!2b0!3e3"++ // The consumer equirect tile endpoint maps.google.com renders — keyless JPEG.+ private const val TILE_URL =+ "https://streetviewpixels-pa.googleapis.com/v1/tile" ++ "?cb_client=maps_sv.tactile&panoid={PANOID}&x={X}&y={Y}&zoom={Z}&nbt=1&fover=2"++ // Browser-like identity — these headers ARE the credential (no key). The tile+ // host also requires the Google referer.+ 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 stitched equirect width so a full-res pyramid (16384×8192 ≈ 400 MB+ // decoded) can't blow up memory; the pan/zoom viewer only needs a sharp mid+ // level. Native pano dimensions are kept (no upscaling — the flat viewer+ // doesn't need a power-of-two texture the way a GL sphere did).+ private const val MAX_TILE_WIDTH = 4096++ private val json = Json { ignoreUnknownKeys = true; isLenient = true }+ private val PANO_ID = Regex("^[A-Za-z0-9_-]{20,25}$")++ // Neighbour de-clutter (Vela): drop same-spot historical panos, cap walk+ // reach, keep only the nearest pano per direction bucket.+ private const val SAME_SPOT_M = 4.0+ private const val MAX_WALK_M = 45.0+ private const val BUCKET_DEG = 30.0++ // Bounded LRU (access-ordered) of resolved metadata, keyed by pano id and by a+ // rounded lat/lng probe. Stores null too (negative cache) so a spot with no+ // imagery isn't refetched on every reselect. Guarded by `synchronized`.+ private val cache = object : LinkedHashMap<String, StreetViewPano?>(16, 0.75f, true) {+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, StreetViewPano?>) = size > 48+ }++ /**+ * Nearest pano to [lat],[lng], or null when there's no imagery nearby or the+ * scrape fails. Never throws.+ */+ suspend fun nearest(lat: Double, lng: Double): StreetViewPano? {+ // ~11 m grid: enough to dedupe repeated selects of the same place without+ // snapping distinct nearby places together.+ val key = "ll:${"%.4f".format(lat)},${"%.4f".format(lng)}"+ synchronized(cache) { if (cache.containsKey(key)) return cache[key] }+ val pano = runCatching { fetchNearest(lat, lng) }.getOrNull()+ synchronized(cache) {+ cache[key] = pano+ if (pano != null) cache[pano.panoId] = pano+ }+ return pano+ }++ /**+ * Metadata for a specific [panoId] — used to walk to a neighbour. Null on+ * failure. Never throws.+ */+ suspend fun byPano(panoId: String): StreetViewPano? {+ synchronized(cache) { if (cache.containsKey(panoId)) return cache[panoId] }+ val pano = runCatching { fetchPano(panoId) }.getOrNull()+ synchronized(cache) { cache[panoId] = pano }+ return pano+ }++ private suspend fun fetchNearest(lat: Double, lng: Double): StreetViewPano? =+ withContext(Dispatchers.IO) {+ val url = META_URL.replace("{LAT}", lat.toString()).replace("{LNG}", lng.toString())+ val body = getText(url) ?: return@withContext null+ parsePano(body, lat, lng)+ }++ private suspend fun fetchPano(panoId: String): StreetViewPano? =+ withContext(Dispatchers.IO) {+ val body = getText(PANO_URL.replace("{PANOID}", panoId)) ?: return@withContext null+ // A by-id fetch has no query point; the parser reads the real position+ // from the response and only uses the fallback when it's missing.+ parsePano(body, 0.0, 0.0).takeIf { it != null && (it.lat != 0.0 || it.lng != 0.0) }+ }++ // --- panorama tiles → one equirect bitmap --------------------------------++ /**+ * Fetch [pano]'s equirectangular tiles at a bounded zoom level and stitch them+ * into one bitmap for the pan/zoom viewer. Null when no tile could be fetched.+ *+ * The pyramid shape is taken from the pano's own [StreetViewPano.levelDims]+ * (modern captures are 512·2^z, pre-2016 are 416·2^z) so an old capture's grid+ * isn't over-requested into black bands.+ */+ suspend fun loadPanorama(pano: StreetViewPano): Bitmap? = withContext(Dispatchers.IO) {+ val dims = pano.levelDims.ifEmpty { List(6) { 512 * (1 shl it) to 256 * (1 shl it) } }+ val z = dims.indexOfLast { it.first in 1..MAX_TILE_WIDTH }.coerceAtLeast(0)+ val (w, h) = dims[z]+ val ts = pano.tileSize.coerceAtLeast(1)+ val cols = (w + ts - 1) / ts+ val rows = (h + ts - 1) / ts+ val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)+ val canvas = Canvas(bmp)++ val placed = coroutineScope {+ val jobs = ArrayList<Deferred<Triple<Int, Int, Bitmap>?>>(cols * rows)+ for (y in 0 until rows) for (x in 0 until cols) {+ jobs += async(Dispatchers.IO) {+ val bytes = tile(pano.panoId, x, y, z) ?: return@async null+ val t = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return@async null+ Triple(x, y, t)+ }+ }+ var n = 0+ for (job in jobs) {+ val t = job.await() ?: continue+ val px = t.first * ts+ val py = t.second * ts+ // Crop edge tiles to the image bounds — past them is padding.+ val srcW = minOf(ts, w - px).coerceAtMost(t.third.width)+ val srcH = minOf(ts, h - py).coerceAtMost(t.third.height)+ if (srcW > 0 && srcH > 0) {+ canvas.drawBitmap(t.third, Rect(0, 0, srcW, srcH), Rect(px, py, px + srcW, py + srcH), null)+ n+++ }+ t.third.recycle()+ }+ n+ }+ if (placed == 0) {+ bmp.recycle()+ null+ } else {+ bmp+ }+ }++ private suspend fun tile(panoId: String, x: Int, y: Int, zoom: Int): ByteArray? {+ val url = TILE_URL+ .replace("{PANOID}", panoId)+ .replace("{X}", x.toString())+ .replace("{Y}", y.toString())+ .replace("{Z}", zoom.toString())+ val (status, bytes) = runCatching {+ NetworkClient.performRequestBytes(url = url, headers = REQUEST_HEADERS, useSystemTrust = true)+ }.getOrNull() ?: return null+ return if (status in 200..299 && bytes.isNotEmpty()) bytes else null+ }++ // --- HTTP + parsing ------------------------------------------------------++ /** GET the body text, or null on any non-2xx / transport error. `useSystemTrust`+ * because these are arbitrary external Google hosts, not pinned first-party. */+ private suspend fun getText(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+ }++ /**+ * Parse a SingleImageSearch / photometa response into a [StreetViewPano].+ * [lat]/[lng] are the fallback position used only when the response omits one.+ * Only the pano id is required; everything else degrades to null. Ported from+ * Vela's StreetViewParser (SF capture 2026-07-15).+ */+ private fun parsePano(raw: String, lat: Double, lng: Double): StreetViewPano? {+ val root = runCatching { json.parseToJsonElement(unwrap(raw)) }.getOrNull() ?: return null+ // Two nestings: SingleImageSearch puts the pano node at root[1]; photometa/v1+ // wraps it one deeper at root[1][0]. Pick whichever carries the [1][1] id.+ val panoNode = root.at(1).takeIf { it.at(1, 1).str()?.let(PANO_ID::matches) == true }+ ?: root.at(1, 0)+ val panoId = panoNode.at(1, 1).str()?.takeIf { PANO_ID.matches(it) }+ ?: firstMatchingString(panoNode) { PANO_ID.matches(it) }+ ?: return null++ val tileSize = panoNode.at(2, 3, 1, 0).int() ?: panoNode.at(2, 3, 1, 1).int() ?: 512+ val levels = panoNode.at(2, 3, 0).arr()?.size ?: 6+ // Per-level [h, w] (nested one deeper) → (w, h). Old captures are 416·2^z.+ val levelDims = panoNode.at(2, 3, 0).arr()?.mapNotNull { lvl ->+ val h = lvl.at(0, 0).int()+ val w = lvl.at(0, 1).int()+ if (w != null && h != null && w > 0 && h > 0) w to h else null+ }.orEmpty()++ val posNode = panoNode.at(5, 0, 1)+ val pLat = posNode.at(0, 2).dbl() ?: lat+ val pLng = posNode.at(0, 3).dbl() ?: lng+ val heading = posNode.at(2, 0).dbl() ?: 0.0++ val address = panoNode.at(3, 2, 0, 0).str()+ val copyright = panoNode.at(4, 0, 0, 0, 0).str()+ val year = panoNode.at(6, 7, 0).int()+ val month = panoNode.at(6, 7, 1).int()++ // Local graph: [ [2,id], _, [ [_,_,lat,lng], … ] ]. Index 0 is this pano.+ val graph = panoNode.at(5, 0, 3, 0).arr().orEmpty()+ val raws = graph.mapNotNull { g ->+ val id = g.at(0, 1).str()?.takeIf { PANO_ID.matches(it) } ?: return@mapNotNull null+ val gLa = g.at(2, 0, 2).dbl() ?: return@mapNotNull null+ val gLn = g.at(2, 0, 3).dbl() ?: return@mapNotNull null+ Triple(id, gLa, gLn)+ }++ val walk = raws.asSequence()+ .filter { it.first != panoId }+ .map { r ->+ val dm = haversine(pLat, pLng, r.second, r.third)+ val bd = bearing(pLat, pLng, r.second, r.third)+ StreetViewLink(r.first, r.second, r.third, bd, dm)+ }+ .filter { it.distanceM in SAME_SPOT_M..MAX_WALK_M }+ .sortedBy { it.distanceM }+ .fold(mutableListOf<StreetViewLink>()) { keep, link ->+ if (keep.none { abs(angleDelta(it.bearingDeg, link.bearingDeg)) < BUCKET_DEG }) keep.add(link)+ keep+ }+ .sortedBy { it.bearingDeg }++ return StreetViewPano(+ panoId = panoId, lat = pLat, lng = pLng, headingDeg = heading,+ tileSize = tileSize, maxZoom = levels, levelDims = levelDims,+ addressLabel = address, copyright = copyright,+ captureYear = year, captureMonth = month, neighbors = walk,+ )+ }++ /** Strip the response envelope: photometa/v1's `)]}'` XSSI guard, or+ * SingleImageSearch's `/**/cb && cb( … )` callback wrapper. */+ private fun unwrap(raw: String): String {+ val t = raw.trim()+ if (t.startsWith(")]}'")) return t.substring(4).trimStart('\n', '\r', ' ')+ val open = t.indexOf('(')+ val close = t.lastIndexOf(')')+ return if (open in 0 until close) t.substring(open + 1, close).trim() else t+ }++ private fun firstMatchingString(el: JsonElement?, pred: (String) -> Boolean): String? {+ when (el) {+ is JsonArray -> for (child in el) firstMatchingString(child, pred)?.let { return it }+ else -> el.str()?.let { if (pred(it)) return it }+ }+ return null+ }++ private fun haversine(aLat: Double, aLng: Double, bLat: Double, bLng: Double): Double {+ val r = 6_371_000.0+ val dLat = Math.toRadians(bLat - aLat)+ val dLng = Math.toRadians(bLng - aLng)+ val h = sin(dLat / 2) * sin(dLat / 2) ++ cos(Math.toRadians(aLat)) * cos(Math.toRadians(bLat)) * sin(dLng / 2) * sin(dLng / 2)+ return 2 * r * atan2(sqrt(h), sqrt(1 - h))+ }++ private fun bearing(aLat: Double, aLng: Double, bLat: Double, bLng: Double): Double {+ val dLng = Math.toRadians(bLng - aLng)+ val y = sin(dLng) * cos(Math.toRadians(bLat))+ val x = cos(Math.toRadians(aLat)) * sin(Math.toRadians(bLat)) -+ sin(Math.toRadians(aLat)) * cos(Math.toRadians(bLat)) * cos(dLng)+ return (Math.toDegrees(atan2(y, x)) + 360) % 360+ }++ /** Signed smallest difference a→b in degrees, in [-180, 180]. */+ private fun angleDelta(a: Double, b: Double): Double {+ var d = (b - a + 540) % 360 - 180+ if (d < -180) d += 360+ return d+ }+}
maps/src/main/java/com/vayunmathur/maps/data/google/StreetViewModels.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/google/StreetViewModels.kt b/maps/src/main/java/com/vayunmathur/maps/data/google/StreetViewModels.ktnew file mode 100644index 0000000000..ae4dbf03ff--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/data/google/StreetViewModels.kt@@ -0,0 +1,52 @@+package com.vayunmathur.maps.data.google++/**+ * A Street View panorama's metadata, resolved from a lat/lng by the keyless+ * `GeoPhotoService.SingleImageSearch` endpoint (the same one Google's own JS Maps+ * API uses — no API key, authorised by referer). Everything the in-app viewer+ * needs to fetch tiles, walk to neighbours, and attribute the imagery; the tiles+ * themselves come from `streetviewpixels-pa.googleapis.com/v1/tile` (also keyless).+ *+ * The equirectangular image is a 2:1 pyramid: at zoom `z` a modern capture is+ * `512·2^z` wide by `256·2^z` tall, cut into [tileSize]² tiles — but the shape is+ * NOT fixed (pre-2016 captures are `416·2^z`), so [levelDims] carries the pano's+ * own per-level dimensions and the tile loader sizes its grid from THOSE.+ *+ * Ported from Vela's `StreetViewPano` (model only; the renderer is the photos-app+ * pan/zoom viewer, not Vela's GLES sphere).+ */+data class StreetViewPano(+ val panoId: String,+ val lat: Double,+ val lng: Double,+ // Capture heading (degrees, true north): the compass direction at the image+ // centre. Kept for attribution/orientation; the flat pan/zoom viewer doesn't+ // reproject by it.+ val headingDeg: Double = 0.0,+ val tileSize: Int = 512,+ // Number of pyramid levels; a full-res equirect is ~400 MB decoded, so the+ // loader picks a level well below the max.+ val maxZoom: Int = 5,+ // Per-level equirect dimensions (width, height), zoom 0 upward, straight from+ // the metadata. Empty → assume the modern 512·2^z shape.+ val levelDims: List<Pair<Int, Int>> = emptyList(),+ // Attribution: the place label Google attaches to the pano, and the copyright.+ val addressLabel: String? = null,+ val copyright: String? = null,+ // Capture date of THIS pano (year, month). Google shows "Image capture: …".+ val captureYear: Int? = null,+ val captureMonth: Int? = null,+ // Walkable neighbours — the panoramas you can step to, one per rough direction.+ // Already de-cluttered from the raw ~100-pano local graph.+ val neighbors: List<StreetViewLink> = emptyList(),+)++/** A neighbouring pano you can walk to: its id, position, and the bearing+distance+ * from the current pano (so the viewer can label a directional step). */+data class StreetViewLink(+ val panoId: String,+ val lat: Double,+ val lng: Double,+ val bearingDeg: Double,+ val distanceM: Double,+)
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 2ad5e8e1fe..75ff23be1a 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt@@ -21,6 +21,7 @@ import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CardDefaults import com.vayunmathur.library.ui.IconCall import com.vayunmathur.library.ui.IconDirections+import com.vayunmathur.library.ui.IconDirectionsWalk import com.vayunmathur.library.ui.IconGlobe import com.vayunmathur.library.ui.IconMenuBook import com.vayunmathur.library.ui.IconSave@@ -34,6 +35,7 @@ import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf@@ -50,12 +52,17 @@ import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp+import androidx.compose.ui.window.Dialog+import androidx.compose.ui.window.DialogProperties import androidx.core.net.toUri import com.vayunmathur.library.util.firstLetterUppercase import com.vayunmathur.maps.R import com.vayunmathur.maps.data.OpeningHours import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.data.google.GooglePoiInfo+import com.vayunmathur.maps.data.google.StreetViewDataSource+import com.vayunmathur.maps.data.google.StreetViewPano+import com.vayunmathur.maps.ui.streetview.StreetViewScreen import com.vayunmathur.maps.data.timeFormat import com.vayunmathur.maps.util.SavedPlacesViewModel import com.vayunmathur.maps.util.SelectedFeatureViewModel@@ -137,6 +144,7 @@ private fun PlaceSheetContent( RestaurantItem({ IconMenuBook() }, stringResource(R.string.menu_label)) { goto(context, it) } } openingHours?.let { OsmHours(it) }+ StreetViewEntry(feature) // Reuse the existing enrichment sections (editorial / photos / popular // times / reviews). The header already shows category · price, so the // enrichment's own subtitle is suppressed to avoid duplication.@@ -144,6 +152,34 @@ private fun PlaceSheetContent( } } +/**+ * "Street View" place-sheet entry (v1 entry point per the port plan). On selection+ * we do a keyless nearest-pano lookup for the place's position; the row only+ * appears when imagery exists nearby. Tapping it opens the full-screen+ * [StreetViewScreen] in a dialog (the photos-style pan/zoom pano viewer).+ */+@Composable+private fun StreetViewEntry(feature: SpecificFeature.RoutableFeature) {+ var pano by remember(feature.position) { mutableStateOf<StreetViewPano?>(null) }+ var show by remember(feature.position) { mutableStateOf(false) }++ LaunchedEffect(feature.position) {+ pano = StreetViewDataSource.nearest(feature.position.latitude, feature.position.longitude)+ }++ pano?.let { p ->+ RestaurantItem({ IconDirectionsWalk() }, stringResource(R.string.street_view)) { show = true }+ if (show) {+ Dialog(+ onDismissRequest = { show = false },+ properties = DialogProperties(usePlatformDefaultWidth = false),+ ) {+ StreetViewScreen(initialPano = p, onClose = { show = false })+ }+ }+ }+}+ @Composable private fun PlaceHeader(name: String, poi: GooglePoiInfo?, hasOsmHours: Boolean) { Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewScreen.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewScreen.kt b/maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewScreen.ktnew file mode 100644index 0000000000..586760ef0a--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewScreen.kt@@ -0,0 +1,231 @@+package com.vayunmathur.maps.ui.streetview++import android.graphics.Bitmap+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.calculatePan+import androidx.compose.foundation.gestures.calculateZoom+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.rememberScrollState+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.FilledTonalButton+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconDirectionsWalk+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.rememberCoroutineScope+import kotlinx.coroutines.launch+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import com.vayunmathur.maps.R+import com.vayunmathur.maps.data.google.StreetViewDataSource+import com.vayunmathur.maps.data.google.StreetViewLink+import com.vayunmathur.maps.data.google.StreetViewPano++/**+ * Full-screen Google Street View viewer.+ *+ * RENDERER: the equirectangular panorama is a single stitched [Bitmap] shown with+ * the **photos app's pan/zoom image renderer** — the manual pinch/pan pattern+ * replicated from `photos/.../ui/PhotoPage.kt`'s `PhotoDetailView` (an+ * `awaitEachGesture` loop driving a `graphicsLayer` scale/translation, plus a+ * double-tap zoom toggle). This is NOT Vela's GLES sphere; it's a flat pannable+ * image, chosen for simplicity and consistency with the photos viewer.+ *+ * Tapping a neighbour steps to the adjacent pano ([StreetViewPano.neighbors]),+ * refetched by id, and the zoom resets for the new image.+ */+@Composable+fun StreetViewScreen(initialPano: StreetViewPano, onClose: () -> Unit) {+ var pano by remember { mutableStateOf(initialPano) }+ var image by remember { mutableStateOf<ImageBitmap?>(null) }+ var loading by remember { mutableStateOf(true) }++ // Load (and reload on pano change) the stitched equirect off the main thread.+ LaunchedEffect(pano.panoId) {+ loading = true+ image = null+ val bmp: Bitmap? = StreetViewDataSource.loadPanorama(pano)+ image = bmp?.asImageBitmap()+ loading = false+ }++ Scaffold(containerColor = Color.Black) { padding ->+ Box(Modifier.fillMaxSize()) {+ val current = image+ when {+ current != null -> ZoomablePanorama(current, key = pano.panoId)+ loading -> CircularProgressIndicator(Modifier.align(Alignment.Center), color = Color.White)+ else -> Text(+ stringResource(R.string.street_view_unavailable),+ color = Color.White,+ modifier = Modifier.align(Alignment.Center),+ )+ }++ IconButton(+ onClick = onClose,+ modifier = Modifier.align(Alignment.TopStart).padding(padding).padding(8.dp),+ ) {+ IconClose(tint = Color.White)+ }++ Column(+ modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth().padding(padding).padding(12.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ if (pano.neighbors.isNotEmpty()) {+ NeighborSteps(pano.neighbors) { link -> stepTo(link) { pano = it } }+ }+ Attribution(pano)+ }+ }+ }+}++/** Load a neighbour pano and, if it resolves, swap to it (else keep the current). */+private suspend fun stepTo(link: StreetViewLink, onResolved: (StreetViewPano) -> Unit) {+ StreetViewDataSource.byPano(link.panoId)?.let(onResolved)+}++@Composable+private fun NeighborSteps(neighbors: List<StreetViewLink>, onStep: suspend (StreetViewLink) -> Unit) {+ val scope = rememberCoroutineScope()+ Row(+ Modifier.horizontalScroll(rememberScrollState()),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ neighbors.forEach { link ->+ FilledTonalButton(onClick = { scope.launch { onStep(link) } }) {+ IconDirectionsWalk(Modifier.size(18.dp))+ Text(+ " ${compass(link.bearingDeg)} · ${link.distanceM.toInt()} m",+ style = MaterialTheme.typography.labelMedium,+ )+ }+ }+ }+}++@Composable+private fun Attribution(pano: StreetViewPano) {+ val date = if (pano.captureYear != null && pano.captureMonth != null) {+ " · ${pano.captureYear}-${pano.captureMonth.toString().padStart(2, '0')}"+ } else {+ ""+ }+ Text(+ (pano.copyright ?: "\u00A9 Google") + date,+ color = Color.White.copy(alpha = 0.7f),+ style = MaterialTheme.typography.labelSmall,+ )+}++/** Compass point (8-wind) for a bearing in degrees. */+private fun compass(bearingDeg: Double): String {+ val dirs = listOf("N", "NE", "E", "SE", "S", "SW", "W", "NW")+ return dirs[(((bearingDeg % 360 + 360) % 360) / 45.0).toInt() % 8]+}++/**+ * The photos-app pan/zoom renderer, replicated: a Compose [Image] transformed by a+ * hoisted scale/offset that a raw `awaitEachGesture` pinch/pan loop drives, with a+ * double-tap zoom toggle. Pan is clamped to the image bounds; zoom is 1×..5×. Not+ * hosted in a pager, so gestures are always consumed once zoomed/pinching. Zoom+ * state is keyed on [key] so it resets when the panorama changes.+ */+@Composable+private fun ZoomablePanorama(image: ImageBitmap, key: Any) {+ var scale by remember(key) { mutableFloatStateOf(1f) }+ var offset by remember(key) { mutableStateOf(Offset.Zero) }+ var size by remember { mutableStateOf(IntSize.Zero) }++ Box(+ Modifier.fillMaxSize()+ .pointerInput(key) {+ detectTapGestures(+ onDoubleTap = {+ if (scale > 1f) {+ scale = 1f+ offset = Offset.Zero+ } else {+ scale = 2.5f+ }+ },+ )+ }+ .pointerInput(key) {+ awaitEachGesture {+ awaitFirstDown(requireUnconsumed = false)+ do {+ val event = awaitPointerEvent()+ val zoomChange = event.calculateZoom()+ val panChange = event.calculatePan()+ val isPinching = zoomChange != 1f+ val isZoomed = scale > 1.01f+ if (isZoomed || isPinching) {+ val newScale = (scale * zoomChange).coerceIn(1f, 5f)+ if (newScale > 1f) {+ val maxX = size.width * (newScale - 1) / 2+ val maxY = size.height * (newScale - 1) / 2+ val next = offset + panChange+ scale = newScale+ offset = Offset(next.x.coerceIn(-maxX, maxX), next.y.coerceIn(-maxY, maxY))+ } else {+ scale = 1f+ offset = Offset.Zero+ }+ event.changes.forEach { it.consume() }+ }+ } while (event.changes.any { it.pressed })+ }+ },+ ) {+ Image(+ bitmap = image,+ contentDescription = null,+ modifier = Modifier.fillMaxSize()+ .background(Color.Black)+ .onGloballyPositioned { size = it.size }+ .graphicsLayer {+ scaleX = scale+ scaleY = scale+ translationX = offset.x+ translationY = offset.y+ },+ contentScale = ContentScale.Fit,+ )+ }+}
maps/src/main/res/values/strings.xml
diff --git a/maps/src/main/res/values/strings.xml b/maps/src/main/res/values/strings.xmlindex 1b048e5229..c7e719e452 100644--- a/maps/src/main/res/values/strings.xml+++ b/maps/src/main/res/values/strings.xml@@ -109,6 +109,15 @@ <string name="opens_at">Opens <xliff:g id="time" example="9 AM">%1$s</xliff:g></string> <!-- Label: Section header for menu --> <string name="menu_label">Menu</string>+ <!-- Place detail: opens the Google Street View panorama viewer. "Street View" is a+ Google product name, so it stays non-translatable. -->+ <string name="street_view" translatable="false">Street View</string>+ <!-- Street View viewer: close button content description. -->+ <string name="street_view_close">Close</string>+ <!-- Street View viewer: shown while the panorama tiles are downloading. -->+ <string name="street_view_loading">Loading Street View…</string>+ <!-- Street View viewer: shown when no panorama could be loaded for this place. -->+ <string name="street_view_unavailable">Street View is not available here</string> <!-- MapPage: Placeholder for map search bar --> <string name="search_placeholder">Search…</string>