Modern Apps git

← Modern-Apps.git

maps: open on current or last known location

Commit
fd50c80fe1b03170f7c2ff06cb517d043e519d04
Author
vayun-mathur <[email protected]>
When
2026-10-08 21:38 UTC (1 month ago)
Parents
5edc877

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 63795a4a21..40756b0868 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -274,10 +274,15 @@ class MainActivity : ComponentActivity() {             selectedVm.userPosition.first { it.latitude != 0.0 || it.longitude != 0.0 }         } -    /** Search bias: the user's live position when known, else the map's default centre. */+    /** Search bias: the user's live position when known, else the persisted last fix, else the map's default centre. */     private fun biasPosition(): GeoPoint {         val p = selectedVm.userPosition.value-        return if (p.latitude != 0.0 || p.longitude != 0.0) p else GeoPoint(FALLBACK_LON, FALLBACK_LAT)+        if (p.latitude != 0.0 || p.longitude != 0.0) return p+        val ds = DataStoreUtils.getInstance(this)+        val lon = ds.getDouble(MapPreferences.KEY_LAST_LON)+        val lat = ds.getDouble(MapPreferences.KEY_LAST_LAT)+        if (lon != null && lat != null && (lat != 0.0 || lon != 0.0)) return GeoPoint(lon, lat)+        return GeoPoint(FALLBACK_LON, FALLBACK_LAT)     }      private fun genericPlace(name: String, lat: Double, lng: Double) =
maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.kt b/maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.ktindex 021e19c1a0..127f0a1494 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.kt@@ -21,6 +21,14 @@ object MapPreferences {     const val KEY_LAYER_SAFETY = "layer_safety"     const val KEY_LAYER_TRANSIT = "layer_transit" +    /**+     * Last known user position (lon/lat doubles). Written on every accepted GPS+     * fix and read back to seed the cold-start camera, so the map opens where+     * the user was rather than the SF fallback. Absent = no fix ever recorded.+     */+    const val KEY_LAST_LON = "last_lon"+    const val KEY_LAST_LAT = "last_lat"+     const val DEFAULT_VOICE_GUIDANCE = true     const val DEFAULT_GLOBE = false     const val DEFAULT_LAYER_TRAFFIC = true
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 d6033162a4..15a175cd87 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -39,12 +39,9 @@ import com.vayunmathur.library.ui.isExpandedWidth import com.vayunmathur.library.ui.rememberFreeHeightSheetState import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.library.map.CameraPosition-import com.vayunmathur.library.map.CameraState-import com.vayunmathur.library.map.GeoPoint import com.vayunmathur.library.map.MapBody import com.vayunmathur.library.map.MoonTextures-import com.vayunmathur.library.map.rememberCameraState+import com.vayunmathur.maps.ui.map.rememberInitialCamera import com.vayunmathur.maps.Route import com.vayunmathur.maps.data.ParkingSpot import com.vayunmathur.maps.data.SpecificFeature@@ -84,9 +81,6 @@ import com.vayunmathur.maps.util.SelectedFeatureViewModel import kotlinx.coroutines.launch import com.vayunmathur.maps.R as MapsR -/** Cold-start camera: San Francisco at z14, where the baked POIs are dense enough to see. */-private val INITIAL_CAMERA = CameraPosition(target = GeoPoint(-122.4194, 37.7749), zoom = 14.0)-  /**  * The map screen.@@ -116,7 +110,7 @@ fun MapPage(     val noResultsMessage = stringResource(MapsR.string.no_results_found)      val chrome = rememberMapChromeState()-    val camera = rememberCameraState(INITIAL_CAMERA)+    val camera = rememberInitialCamera(viewModel)      val selectedFeature by viewModel.selectedFeature.collectAsState()     // Keep the router's plan order on the visible tab: routes plans the
maps/src/main/java/com/vayunmathur/maps/ui/map/MapInitialCamera.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapInitialCamera.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapInitialCamera.ktnew file mode 100644index 0000000000..33f38d04d4--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapInitialCamera.kt@@ -0,0 +1,70 @@+package com.vayunmathur.maps.ui.map++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+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.platform.LocalContext+import com.vayunmathur.library.map.CameraPosition+import com.vayunmathur.library.map.CameraState+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.map.rememberCameraState+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.maps.data.MapPreferences+import com.vayunmathur.maps.util.SelectedFeatureViewModel++/** Cold-start fallback: San Francisco at z14, where the baked POIs are dense enough to see. */+private val FALLBACK_CAMERA = CameraPosition(target = GeoPoint(-122.4194, 37.7749), zoom = 14.0)++/** Zoom the cold-start camera adopts once the user's position is known. */+private const val FIRST_FIX_ZOOM = 14.0++/**+ * Cold-start camera for the map screen.+ *+ * Seeded from the persisted last fix so the map opens where the user was, not+ * the SF fallback. DataStore's snapshot read can be empty on a truly cold+ * process (not yet hydrated), so the first live fix still centers below —+ * either way the zoom stays at the browse default.+ *+ * The centering runs once: it is skipped when a deep link or an existing+ * selection owns the camera, and latched in that case too, so consuming the+ * deep link later cannot re-trigger a center that would steal it back.+ */+@Composable+fun rememberInitialCamera(viewModel: SelectedFeatureViewModel): CameraState {+    val context = LocalContext.current+    val dataStore = remember(context) { DataStoreUtils.getInstance(context) }+    val snapshotLast = remember(dataStore) {+        val lon = dataStore.getDouble(MapPreferences.KEY_LAST_LON)+        val lat = dataStore.getDouble(MapPreferences.KEY_LAST_LAT)+        if (lon != null && lat != null && (lat != 0.0 || lon != 0.0)) GeoPoint(lon, lat) else null+    }+    val camera = rememberCameraState(+        snapshotLast?.let { CameraPosition(target = it, zoom = FIRST_FIX_ZOOM) } ?: FALLBACK_CAMERA,+    )++    val userPosition by viewModel.userPosition.collectAsState()+    val selectedFeature by viewModel.selectedFeature.collectAsState()+    val pendingFocus by viewModel.pendingFocus.collectAsState()+    var centeredOnFix by remember { mutableStateOf(false) }+    LaunchedEffect(userPosition, selectedFeature, pendingFocus) {+        if (centeredOnFix) return@LaunchedEffect+        if (userPosition.latitude == 0.0 && userPosition.longitude == 0.0) return@LaunchedEffect+        if (pendingFocus != null || selectedFeature != null) {+            centeredOnFix = true+            return@LaunchedEffect+        }+        centeredOnFix = true+        camera.animateTo(+            camera.position.copy(+                target = userPosition,+                zoom = FIRST_FIX_ZOOM.coerceAtLeast(camera.position.zoom),+            ),+        )+    }+    return camera+}
maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt b/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.ktindex 51b041fffa..eb10f2de80 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt@@ -96,6 +96,21 @@ class FrameworkLocationManager(context: Context) : SensorEventListener {             )         } +        // Emit the OS last-known fix immediately so the UI opens on the user's+        // current (or last known) location instead of waiting for the first+        // live fix. Any last-known beats the SF fallback, so no staleness+        // filter here — recency filtering is for the live stream only.+        lastKnownLocation()?.let { location ->+            lastFix = Fix(+                fromGps = location.provider == LocationManager.GPS_PROVIDER,+                accuracyM = if (location.hasAccuracy()) location.accuracy else 0f,+                elapsedRealtimeNanos = location.elapsedRealtimeNanos,+            )+            lastLocation = location+            val heading = if (location.hasBearing()) location.bearing else currentHeading+            onUpdate?.invoke(GeoPoint(location.longitude, location.latitude), heading)+        }+         // 2. Setup Sensor Updates (Compass)         sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)?.also { acc ->             sensorManager.registerListener(this, acc, SensorManager.SENSOR_DELAY_UI)@@ -128,6 +143,33 @@ class FrameworkLocationManager(context: Context) : SensorEventListener {         lastEmittedHeading = null     } +    /**+     * Best last-known position the OS has cached (GPS preferred, then network),+     * or null when neither provider has one. Called with location permission+     * already granted — the caller gates on it — so a SecurityException here+     * means the provider state changed mid-call and is treated as no fix.+     */+    @SuppressLint("MissingPermission")+    private fun lastKnownLocation(): Location? {+        val providers = listOf(+            LocationManager.GPS_PROVIDER,+            LocationManager.NETWORK_PROVIDER,+        )+        var best: Location? = null+        for (provider in providers) {+            if (!locationManager.isProviderEnabled(provider)) continue+            val fix = runCatching { locationManager.getLastKnownLocation(provider) }.getOrNull()+                ?: continue+            // A (0,0) last-known is the OS having nothing real, not the Gulf of Guinea.+            if (fix.latitude == 0.0 && fix.longitude == 0.0) continue+            val current = best+            if (current == null || fix.elapsedRealtimeNanos > current.elapsedRealtimeNanos) {+                best = fix+            }+        }+        return best+    }+     override fun onSensorChanged(event: SensorEvent) {         if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) {             accelerometerReading = event.values.copyOf()
maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.ktindex 7ebfae18e9..3769f4e823 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt@@ -27,6 +27,8 @@ import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.maps.data.MapPreferences  class SelectedFeatureViewModel(application: Application): AndroidViewModel(application) {     private val _selectedFeature = MutableStateFlow<SpecificFeature?>(null)@@ -72,6 +74,20 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli     private companion object {         const val PARTIAL_MIN_GROWTH = 5         const val PARTIAL_MIN_INTERVAL_MS = 2_000L++        /**+         * Minimum movement (metres, equirectangular — fine at this scale)+         * before the persisted position is rewritten.+         */+        private const val MIN_PERSIST_DISTANCE_M = 50.0++        /** Equirectangular distance in metres — fine at the 50 m gate scale. */+        private fun distanceM(a: GeoPoint, b: GeoPoint): Double {+            val dx = (a.longitude - b.longitude) * 111_320.0 *+                kotlin.math.cos(Math.toRadians((a.latitude + b.latitude) / 2.0))+            val dy = (a.latitude - b.latitude) * 110_540.0+            return kotlin.math.sqrt(dx * dx + dy * dy)+        }     }      /** A pending request for the map to fly to [position] (at [zoom] when set) and@@ -96,6 +112,14 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli      val locationManager = FrameworkLocationManager(application) +    private val dataStore = DataStoreUtils.getInstance(application)++    /**+     * Last fix persisted, throttled by distance — DataStore rewrites the whole+     * file per edit, so a standing-still phone should not rewrite it every second.+     */+    private var lastPersisted: GeoPoint? = null+     // Hidden-WebView reviews scraper (keyless; Google 404'd the old reviews RPC). Holds a single     // WebView built from the application Context, serialized + idle-reaped internally.     private val webReviews = WebReviewsFetcher(application)@@ -105,6 +129,7 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli             onUpdateReceived = { position, bearing ->                 _userPosition.value = position                 _userBearing.value = bearing+                persistPosition(position)             },             onAccuracyReceived = { accuracy ->                 _userHeadingAccuracy.value = accuracy@@ -112,6 +137,25 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli         )     } +    /**+     * Persist the live fix for the next cold start, throttled by distance so a+     * stationary phone does not rewrite DataStore every second. Fire-and-forget+     * on `viewModelScope`: a lost write only costs one stale open.+     */+    private fun persistPosition(position: GeoPoint) {+        // (0,0) is this VM's "no fix" sentinel — never persist it over a real fix.+        if (position.latitude == 0.0 && position.longitude == 0.0) return+        val previous = lastPersisted+        if (previous != null && distanceM(previous, position) < MIN_PERSIST_DISTANCE_M) return+        lastPersisted = position+        viewModelScope.launch {+            runCatching {+                dataStore.setDouble(MapPreferences.KEY_LAST_LON, position.longitude)+                dataStore.setDouble(MapPreferences.KEY_LAST_LAT, position.latitude)+            }+        }+    }+     override fun onCleared() {         // Unregister GPS + sensor listeners so the radio doesn't keep draining         // battery after the user navigates away from the map module.