Modern Apps git

← Modern-Apps.git

maps: ambient speed readout while moving outside navigation

Commit
214f1edf35f3a6c2450b4a950dfb6a626eac1822
Author
Vayun Mathur <[email protected]>
When
2026-11-08 20:12 UTC (27 days ago)
Parents
bd207f4
Show the navigation speedometer whenever the user moves at or above
10 mph / 15 km/h, even outside navigation. It reuses SpeedWidget
itself — no second speed view — wrapped in a new AmbientSpeed
composable that adds a visibility latch (show at 10 mph / 15 km/h,
hide below 8 mph / 12 km/h) so hovering at the threshold does not
flicker. The unit follows the posted limit's authored unit when one
is known, otherwise the regional setting, using the posted limit the
nav call site already threads through; the latch computes the same
decision so the two agree.

Plumbing: FrameworkLocationManager.onUpdate gains the GPS speed
(0 when the fix has none), SelectedFeatureViewModel exposes it as
userSpeedMps, MapPage collects it into MapPageScope. Placement lives
in AmbientSpeedOverlay (BoxScope, bottom-start above the scale bar
via the new MapChromeMetrics.aboveScaleBar, lifted by the measured
search-bar height like the FAB stack) and shows only while browsing
with no sheet up — navigation owns that corner while navigating.

FileLength keeps MapContentBox under its limit: the pre-existing
search-bar block moves verbatim into MapSearchBarSection (a
MapPageScope member extension taking the caller's aligned modifier,
since a top-level fun cannot hold both receivers).

Verified: :maps:compileDevKotlin and :maps:checkDevAarMetadata green;
:maps:lint reports no errors in the touched files (remaining errors
are pre-existing in untouched files).

Diff

maps/src/main/java/com/vayunmathur/maps/ui/MapContentBox.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapContentBox.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapContentBox.ktindex 08cd604a45..a38e11d08e 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapContentBox.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapContentBox.kt@@ -11,7 +11,6 @@ import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import com.vayunmathur.library.map.GeoPoint@@ -31,13 +30,11 @@ import com.vayunmathur.maps.ui.map.MapChromeState import com.vayunmathur.maps.ui.map.MapFabStack import com.vayunmathur.maps.ui.map.MapOverlay import com.vayunmathur.maps.ui.map.MapOverlays-import com.vayunmathur.maps.ui.map.MapSearchBar import com.vayunmathur.maps.ui.map.MapSurface import com.vayunmathur.maps.ui.map.NavigationCameraFollow import com.vayunmathur.maps.ui.map.WaypointList+import com.vayunmathur.maps.ui.nav.AmbientSpeedOverlay import com.vayunmathur.maps.ui.streetview.StreetViewPegman-import com.vayunmathur.maps.ui.theme.MapChromeMetrics-import com.vayunmathur.maps.util.visibleBoundsOrWorld import kotlin.math.roundToInt import kotlinx.coroutines.launch @@ -174,41 +171,10 @@ internal fun MapPageScope.MapContentBox(                         }                     } -                    // The search entry point, where the top app bar's used to be but at the other-                    // end of the screen. Browse-only: an open sheet — either of them — owns the-                    // bottom and brings its own field or its own title.-                    if (searchBarVisible) {-                        MapSearchBar(-                            onOpenSearch = { query -> openSearch(query, null) },-                            onContactAddress = { address ->-                                val bbox = camera.visibleBoundsOrWorld()-                                searchViewModel.resolveAndSelect(-                                    address,-                                    (bbox.north + bbox.south) / 2.0,-                                    (bbox.east + bbox.west) / 2.0,-                                ) { place ->-                                    if (place != null) {-                                        viewModel.stashRouteSelection()-                                        // Fly there and open the peek pane, the same direct-open-                                        // path a geo:/maps deep link takes.-                                        viewModel.selectAndFocus(-                                            place,-                                            zoom = (camera.position.zoom).coerceAtLeast(14.0),-                                        )-                                    } else {-                                        messenger.show(noResultsMessage)-                                    }-                                }-                            },-                            modifier = Modifier-                                .align(Alignment.BottomCenter)-                                // Measured, not assumed: the bar's height is what the FAB stack-                                // and the scale bar have to clear, and it moves with the font-                                // scale. Outside the padding, so the margin is included.-                                .onSizeChanged { onSearchBarLift(it.height) }-                                .padding(MapChromeMetrics.chromeMargin),-                        )-                    }+                    // The search entry point; see [MapSearchBarSection].+                    MapSearchBarSection(+                        modifier = Modifier.align(Alignment.BottomCenter),+                    )                      // Browse controls, plus the layers and settings buttons, which stay out while                     // a place is selected and ride above the sheet — see [MapFabStack].@@ -285,6 +251,16 @@ internal fun MapPageScope.MapContentBox(                         route = navSession.route,                     ) +                    // Ambient speed readout: the navigation speedometer while moving,+                    // even outside navigation; see [AmbientSpeedOverlay].+                    AmbientSpeedOverlay(+                        visible = browsing && searchRequest == null,+                        speedMps = userSpeedMps,+                        postedLimit = chrome.postedLimit,+                        darkBasemap = darkMap,+                        liftPx = if (searchBarVisible) searchBarLiftPx else 0,+                    )+                     MapOverlays(                         overlay = chrome.overlay,                         onDismiss = { chrome.dismissOverlay() },
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 f9b8bef3f3..c2eccfc483 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -133,6 +133,7 @@ fun MapPage(     val userPosition by viewModel.userPosition.collectAsState()     val userBearing by viewModel.userBearing.collectAsState()     val userHeadingAccuracy by viewModel.userHeadingAccuracy.collectAsState()+    val userSpeedMps by viewModel.userSpeedMps.collectAsState()      val savedList by savedPlacesViewModel.saved.collectAsState()     // The starred list drawn as one pin set, deduped.@@ -278,6 +279,7 @@ fun MapPage(         userPosition = userPosition,         userBearing = userBearing,         userHeadingAccuracy = userHeadingAccuracy,+        userSpeedMps = userSpeedMps,         savedPins = savedPins,         parkingSpot = parkingSpot,         searchResults = searchResults,
maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.ktindex ea26e7f7e8..f49bd5eb7d 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.kt@@ -118,6 +118,8 @@ internal class MapPageScope(     val userPosition: GeoPoint,     val userBearing: Float?,     val userHeadingAccuracy: Int,+    /** Latest GPS speed in m/s (0 when the fix carries none), for the ambient speed readout. */+    val userSpeedMps: Float,     val savedPins: List<SavedPlace>,     val parkingSpot: ParkingSpot?,     val searchResults: List<SearchResult>,
maps/src/main/java/com/vayunmathur/maps/ui/MapSearchBarSection.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapSearchBarSection.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapSearchBarSection.ktnew file mode 100644index 0000000000..59209880e2--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapSearchBarSection.kt@@ -0,0 +1,57 @@+package com.vayunmathur.maps.ui++import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.layout.onSizeChanged+import com.vayunmathur.maps.ui.map.MapSearchBar+import com.vayunmathur.maps.ui.theme.MapChromeMetrics+import com.vayunmathur.maps.util.visibleBoundsOrWorld++/**+ * The search entry point, moved out of [MapContentBox] so no ui file exceeds+ * the [FileLength] limit. A member extension so it can read the page scope —+ * see MapPageScope for why the scope exists instead of widening it.+ *+ * Takes [modifier] instead of placing itself: the caller sits in the content+ * [Box][androidx.compose.foundation.layout.Box] and aligns it bottom-center.+ */+@Composable+internal fun MapPageScope.MapSearchBarSection(+    modifier: Modifier = Modifier,+) {+    // The search entry point, where the top app bar's used to be but at the other+    // end of the screen. Browse-only: an open sheet — either of them — owns the+    // bottom and brings its own field or its own title.+    if (searchBarVisible) {+        MapSearchBar(+            onOpenSearch = { query -> openSearch(query, null) },+            onContactAddress = { address ->+                val bbox = camera.visibleBoundsOrWorld()+                searchViewModel.resolveAndSelect(+                    address,+                    (bbox.north + bbox.south) / 2.0,+                    (bbox.east + bbox.west) / 2.0,+                ) { place ->+                    if (place != null) {+                        viewModel.stashRouteSelection()+                        // Fly there and open the peek pane, the same direct-open+                        // path a geo:/maps deep link takes.+                        viewModel.selectAndFocus(+                            place,+                            zoom = (camera.position.zoom).coerceAtLeast(14.0),+                        )+                    } else {+                        messenger.show(noResultsMessage)+                    }+                }+            },+            modifier = modifier+                // Measured, not assumed: the bar's height is what the FAB stack+                // and the scale bar have to clear, and it moves with the font+                // scale. Outside the padding, so the margin is included.+                .onSizeChanged { onSearchBarLift(it.height) }+                .padding(MapChromeMetrics.chromeMargin),+        )+    }+}
maps/src/main/java/com/vayunmathur/maps/ui/nav/AmbientSpeed.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/nav/AmbientSpeed.kt b/maps/src/main/java/com/vayunmathur/maps/ui/nav/AmbientSpeed.ktnew file mode 100644index 0000000000..da0265c822--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/nav/AmbientSpeed.kt@@ -0,0 +1,58 @@+package com.vayunmathur.maps.ui.nav++import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import com.vayunmathur.maps.data.PostedLimit+import com.vayunmathur.maps.util.isImperialUnits++private const val MPH_TO_MPS = 0.44704+private const val KMH_TO_MPS = 1.0 / 3.6++/** Show at or above 10 mph, hide below 8 mph: the 2 mph band stops flicker at the threshold. */+private const val SHOW_MPH = 10.0+private const val HIDE_MPH = 8.0++/** Show at or above 15 km/h, hide below 12 km/h: the metric mirror of the mph band. */+private const val SHOW_KMH = 15.0+private const val HIDE_KMH = 12.0++/**+ * The navigation speedometer, shown while moving even outside navigation.+ *+ * This is [SpeedWidget] itself — not a second speed view — with a visibility+ * latch around it: it appears once the GPS speed reaches 10 mph / 15 km/h and+ * stays until it drops below 8 mph / 12 km/h, so hovering at the threshold+ * does not flicker it. The unit follows the posted limit's authored unit when+ * one is known, otherwise the regional setting — the same decision+ * [SpeedWidget] makes, computed here too so the latch and the readout agree.+ *+ * Below the show threshold (stationary or slow) this composes nothing.+ */+@Composable+fun AmbientSpeed(+    speedMps: Float,+    postedLimit: PostedLimit?,+    darkBasemap: Boolean,+    modifier: Modifier = Modifier,+) {+    val useMph = postedLimit?.displayIsMph ?: isImperialUnits()+    val showAt = (if (useMph) SHOW_MPH * MPH_TO_MPS else SHOW_KMH * KMH_TO_MPS).toFloat()+    val hideBelow = (if (useMph) HIDE_MPH * MPH_TO_MPS else HIDE_KMH * KMH_TO_MPS).toFloat()+    // A latch, not a plain threshold: convergent (idempotent boolean writes),+    // so assigning during composition settles instead of looping.+    var visible by remember { mutableStateOf(false) }+    if (speedMps >= showAt) visible = true+    else if (speedMps < hideBelow) visible = false+    if (!visible) return+    SpeedWidget(+        speedMps = speedMps,+        postedLimit = postedLimit,+        modifier = modifier,+        defaultMph = useMph,+        darkBasemap = darkBasemap,+    )+}
maps/src/main/java/com/vayunmathur/maps/ui/nav/AmbientSpeedOverlay.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/nav/AmbientSpeedOverlay.kt b/maps/src/main/java/com/vayunmathur/maps/ui/nav/AmbientSpeedOverlay.ktnew file mode 100644index 0000000000..fbed87f57f--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/nav/AmbientSpeedOverlay.kt@@ -0,0 +1,47 @@+package com.vayunmathur.maps.ui.nav++import androidx.compose.foundation.layout.BoxScope+import androidx.compose.foundation.layout.WindowInsets+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.systemBars+import androidx.compose.foundation.layout.windowInsetsPadding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.IntOffset+import com.vayunmathur.maps.data.PostedLimit+import com.vayunmathur.maps.ui.theme.MapChromeMetrics++/**+ * Browse-mode placement for [AmbientSpeed]: bottom-start, above the scale bar,+ * lifted by [liftPx] so it clears the search bar instead of sitting behind it.+ *+ * The caller owns the browse-only gate (no navigation, no sheet up) via+ * [visible]; while hidden this composes nothing, so the latch inside+ * [AmbientSpeed] restarts and the readout reappears only once the speed again+ * reaches the show threshold.+ */+@Composable+fun BoxScope.AmbientSpeedOverlay(+    visible: Boolean,+    speedMps: Float,+    postedLimit: PostedLimit?,+    darkBasemap: Boolean,+    liftPx: Int,+) {+    if (!visible) return+    AmbientSpeed(+        speedMps = speedMps,+        postedLimit = postedLimit,+        darkBasemap = darkBasemap,+        modifier = Modifier+            .align(Alignment.BottomStart)+            .offset { IntOffset(0, -liftPx) }+            .windowInsetsPadding(WindowInsets.systemBars)+            .padding(+                start = MapChromeMetrics.chromeMargin,+                bottom = MapChromeMetrics.aboveScaleBar,+            ),+    )+}
maps/src/main/java/com/vayunmathur/maps/ui/theme/MapChromeMetrics.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/theme/MapChromeMetrics.kt b/maps/src/main/java/com/vayunmathur/maps/ui/theme/MapChromeMetrics.ktindex 85e8e4f09e..1e1fdfdb41 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/theme/MapChromeMetrics.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/theme/MapChromeMetrics.kt@@ -45,6 +45,16 @@ object MapChromeMetrics {     /** Clearance for the full-width step list, which tucks closer than free-floating chrome. */     val aboveEtaStripTight: Dp = etaStripHeight + 4.dp +    /**+     * Clearance for chrome sitting directly above the scale bar.+     *+     * The bar is a labelSmall line (16 dp) + 8 dp vertical padding + a 2 dp gap+     * + a 3 dp rule ≈ 29 dp, rounded up so the pill never kisses it. An+     * estimate like [etaStripHeight], for the same reason: one shared number+     * beats a magic one at each call site.+     */+    val aboveScaleBar: Dp = 32.dp + 12.dp+     /**      * Radius of the tolerance box around a tap used to hit-test map pins.      *
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 576475ecce..8bd0e808a0 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt@@ -27,10 +27,11 @@ class FrameworkLocationManager(context: Context) : SensorEventListener {     private val rotationMatrix = FloatArray(9)     private val orientationAngles = FloatArray(3) -    // Callback to pass both GeoPoint and Heading (Compass). The heading is null until a+    // Callback to pass GeoPoint, heading (compass), and speed. The heading is null until a     // real one has been seen: "unknown" and "due north" are different things, and the map-    // draws the puck's bearing cone only for the second.-    private var onUpdate: ((GeoPoint, Float?) -> Unit)? = null+    // draws the puck's bearing cone only for the second. Speed is m/s, 0 when the fix+    // carries none — same convention as the navigation service.+    private var onUpdate: ((GeoPoint, Float?, Float) -> Unit)? = null     // Callback for magnetometer accuracy so the UI can prompt for calibration.     private var onAccuracy: ((Int) -> Unit)? = null     private var lastLocation: Location? = null@@ -56,7 +57,7 @@ class FrameworkLocationManager(context: Context) : SensorEventListener {      @SuppressLint("MissingPermission")     fun startUpdates(-        onUpdateReceived: (GeoPoint, Float?) -> Unit,+        onUpdateReceived: (GeoPoint, Float?, Float) -> Unit,         onAccuracyReceived: (Int) -> Unit = {},     ): LocationListener {         this.onUpdate = onUpdateReceived@@ -102,7 +103,7 @@ class FrameworkLocationManager(context: Context) : SensorEventListener {                 // the next sensor sample compares against what the UI just drew                 // rather than a pre-fix heading.                 if (location.hasBearing()) lastEmittedHeading = location.bearing-                onUpdate?.invoke(point, heading)+                onUpdate?.invoke(point, heading, speedMps)             }             @Deprecated("Overrides deprecated LocationListener.onStatusChanged")             override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}@@ -147,7 +148,8 @@ class FrameworkLocationManager(context: Context) : SensorEventListener {                 accuracyM = lastFix!!.accuracyM,                 sinceNanos = lastFix!!.elapsedRealtimeNanos,             )-            onUpdate?.invoke(point, heading)+            val speedMps = if (location.hasSpeed()) location.speed else 0f+            onUpdate?.invoke(point, heading, speedMps)         }          // 2. Setup Sensor Updates (Compass)@@ -257,7 +259,8 @@ class FrameworkLocationManager(context: Context) : SensorEventListener {                 if (!it.hasBearing() && moved >= HEADING_EMIT_DEGREES) {                     lastEmittedHeading = currentHeading                     val point = positionHold?.drawn ?: GeoPoint(it.longitude, it.latitude)-                    onUpdate?.invoke(point, currentHeading)+                    val speedMps = if (it.hasSpeed()) it.speed else 0f+                    onUpdate?.invoke(point, currentHeading, speedMps)                 }             }         }
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 12ebd6eb24..ab73545abb 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt@@ -120,6 +120,10 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli     private val _userBearing = MutableStateFlow<Float?>(null)     val userBearing = _userBearing.asStateFlow() +    /** Latest GPS speed in m/s (0 when the fix carries none), for the ambient speed readout. */+    private val _userSpeedMps = MutableStateFlow(0f)+    val userSpeedMps = _userSpeedMps.asStateFlow()+     // Magnetometer accuracy backing the compass calibration banner. Defaults to     // HIGH so the banner stays hidden until the sensor reports a lower value.     private val _userHeadingAccuracy = MutableStateFlow(SensorManager.SENSOR_STATUS_ACCURACY_HIGH)@@ -148,9 +152,10 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli      init {         locationManager.startUpdates(-            onUpdateReceived = { position, bearing ->+            onUpdateReceived = { position, bearing, speedMps ->                 _userPosition.value = position                 _userBearing.value = bearing+                _userSpeedMps.value = speedMps                 persistPosition(position)             },             onAccuracyReceived = { accuracy ->