Modern Apps git

← Modern-Apps.git

maps: render baked transit stops and delete GET /api/v1/map/stops

Commit
eddb650be6f8c55460ef1842b1d7a31d2608da79
Author
vayun-mathur <[email protected]>
When
2026-08-21 04:23 UTC (3 months ago)
Parents
113fbca
The stop pins now come from the transit_stops source-layer in the v5 basemap, on the shared VectorSource the admin and POI overlays already use -- a second source on the same PMTiles triggers a directory parse error. toTransitStop reads its coordinates from the point geometry, since a baked tile carries no lat/lng properties, and takes motis_id as the stop id. Stops are coloured by route_type so rail reads differently from bus. That removes a network round-trip on every camera idle for data that never changes, and with it the last coordinate-to-MOTIS-id lookup. The realtime overlay instead uses ids baked into the pack in TRX2 v5: RawStep gains boardStopId/alightStopId on its transit-only tail, whose JNI descriptor is duplicated across the driving and transit call sites and was edited identically in both. The departure board needs its overlay before it knows its stop, so a new local nearestStopMotisIdNative names it; the same accessor now backs openNearestStop, which no longer needs the network at all. A leg or pack with no baked id degrades to schedule-only rather than failing.

Diff

maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.ktindex b5d584ed62..334a175029 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt@@ -10,27 +10,27 @@ import java.time.OffsetDateTime /**  * Online public-transit data source (P10) backed by **Transitous** — a free,  * community-hosted aggregation of open GTFS / GTFS-RT feeds — via its **MOTIS**- * REST API. Two calls are exposed:+ * REST API. One call is exposed:  *- *  - [stopsInBbox] — nearby stops for the current viewport (`/api/v1/map/stops`,- *    the same endpoint the MOTIS web map uses to draw stop dots), for the- *    overlay layer.  *  - [departures] — the live board for one stop (`/api/v1/stoptimes`): route  *    short name, headsign, scheduled + realtime time, delay, platform.  *+ * This is the ONLY endpoint left, and the only genuinely realtime thing in the+ * system. Stops used to come from `/api/v1/map/stops` per viewport; they are+ * static data, so they are now baked into the basemap as the `transit_stops`+ * layer, along with the MOTIS stop id this endpoint needs. Journey planning used+ * to fall back to `/api/v1/plan`; the on-device RAPTOR planner is now the only+ * planner.+ *  * Design mirrors [com.vayunmathur.maps.data.google.GooglePoiDiscovery]:  *  - an `object` singleton, all network on [Dispatchers.IO];  *  - **never throws** — every public call returns empty on any failure so a  *    flaky feed or a MOTIS schema drift degrades gracefully;- *  - **brief caching**: stops are cached per rounded viewport (they rarely- *    change); departures are cached per stop for only [DEPARTURES_TTL_MS] since- *    they are live.- *- * ONLINE-ONLY (P11 adds offline transit from bundled GTFS). Routing is- * untouched — this is a read-only board.+ *  - **brief caching**: departures are cached per stop for only+ *    [DEPARTURES_TTL_MS] since they are live.  *  * NOTE (on-device): the live MOTIS fetch needs a device/emulator with network- * and cannot be exercised at compile time; the endpoints/parse below are+ * and cannot be exercised at compile time; the endpoint/parse below is  * verified by shape only.  */ object TransitousDataSource {@@ -40,16 +40,13 @@ object TransitousDataSource {     /** Cap departures requested per board so a busy hub stays scrollable. */     private const val DEPARTURE_COUNT = 30 -    /** Cap stops per viewport so a dense metro area doesn't flood the overlay. */-    private const val MAX_STOPS = 200-     /** Departures are live — cache only very briefly to smooth refresh taps. */     private const val DEPARTURES_TTL_MS = 20_000L      /**      * How long a *failed* fetch is remembered. Distinct from (and far shorter-     * than) the success TTLs: one offline attempt used to poison the departures-     * cache for the full 20 s and the stops cache indefinitely.+     * than) the success TTL: one offline attempt used to poison the departures+     * cache for the full 20 s.      */     private const val FAILURE_TTL_MS = 3_000L @@ -68,38 +65,11 @@ object TransitousDataSource {             System.currentTimeMillis() - at < if (ok) okTtlMs else FAILURE_TTL_MS     } -    // Stops LRU keyed on the rounded viewport box (stops are static-ish).-    private data class BboxKey(val minLat: Double, val minLon: Double, val maxLat: Double, val maxLon: Double)-    private val stopsCache = object : LinkedHashMap<BboxKey, Cached<List<TransitStop>>>(16, 0.75f, true) {-        override fun removeEldestEntry(eldest: MutableMap.MutableEntry<BboxKey, Cached<List<TransitStop>>>) = size > 32-    }-     // Departures cache keyed on stop id, with a short TTL (live data).     private val departuresCache = object : LinkedHashMap<String, Cached<List<Departure>>>(16, 0.75f, true) {         override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Cached<List<Departure>>>) = size > 32     } -    /**-     * Stops within the viewport box. Never throws — returns an empty list on any-     * failure. LRU-cached on the box rounded to ~100 m so small pans reuse the-     * previous fetch; a failed fetch is only remembered for [FAILURE_TTL_MS].-     */-    suspend fun stopsInBbox(-        minLat: Double,-        minLon: Double,-        maxLat: Double,-        maxLon: Double,-    ): List<TransitStop> {-        val key = BboxKey(round3(minLat), round3(minLon), round3(maxLat), round3(maxLon))-        synchronized(stopsCache) {-            stopsCache[key]?.let { if (it.isFresh(Long.MAX_VALUE)) return it.value }-        }-        val fetched = runCatching { fetchStops(minLat, minLon, maxLat, maxLon) }-        val stops = fetched.getOrDefault(emptyList())-        synchronized(stopsCache) { stopsCache[key] = Cached(stops, fetched.isSuccess) }-        return stops-    }-     /**      * Live departures for [stopId]. Never throws — empty on failure. Cached for      * [DEPARTURES_TTL_MS] on success and only [FAILURE_TTL_MS] on failure; pass@@ -117,41 +87,6 @@ object TransitousDataSource {         return deps     } -    /**-     * Live board for the MOTIS stop nearest `(lat, lon)`. MOTIS stop ids share no-     * namespace with the baked `.transit` pack, so the offline planner locates a-     * stop's realtime data by proximity — the same trick-     * [com.vayunmathur.maps.util.TransitStopsViewModel.openNearestStop] uses.-     * Empty when nothing is near or the fetch fails.-     */-    suspend fun departuresNear(lat: Double, lon: Double): List<Departure> {-        // ~1.1 km search box, then the closest stop within it.-        val d = 0.01-        val nearest = stopsInBbox(lat - d, lon - d, lat + d, lon + d).minByOrNull { s ->-            val dLat = s.lat - lat-            val dLon = s.lon - lon-            dLat * dLat + dLon * dLon-        } ?: return emptyList()-        return departures(nearest.id)-    }--    private suspend fun fetchStops(-        minLat: Double,-        minLon: Double,-        maxLat: Double,-        maxLon: Double,-    ): List<TransitStop> = withContext(Dispatchers.IO) {-        // MOTIS map/stops takes the box corners as "lat,lon" min/max pairs.-        val url = "$BASE_URL/api/v1/map/stops" +-            "?min=${enc("$minLat,$minLon")}&max=${enc("$maxLat,$maxLon")}"-        val stops: List<MotisMapStop> = NetworkClient.getJson(url, REQUEST_HEADERS, useSystemTrust = true)-        stops.asSequence()-            .map { TransitStop(id = it.id, name = it.name.ifBlank { it.id }, lat = it.lat, lon = it.lon) }-            .distinctBy { it.id }-            .take(MAX_STOPS)-            .toList()-    }-     private suspend fun fetchDepartures(stopId: String): List<Departure> = withContext(Dispatchers.IO) {         val url = "$BASE_URL/api/v1/stoptimes" +             "?stopId=${enc(stopId)}&n=$DEPARTURE_COUNT&arriveBy=false"@@ -190,6 +125,5 @@ object TransitousDataSource {             .getOrNull()     } -    private fun round3(v: Double): Double = Math.round(v * 1000.0) / 1000.0     private fun enc(s: String): String = URLEncoder.encode(s, "UTF-8") }
maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.ktindex 5a440df6f4..ff670ff704 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt@@ -15,9 +15,20 @@ import kotlinx.serialization.Serializable  *    [com.vayunmathur.library.network.NetworkClient] JSON is  *    `ignoreUnknownKeys`, so a MOTIS schema change degrades to nulls rather  *    than throwing (mirrors the Google-scrape null-safety convention).+ *+ * Only `GET /api/v1/stoptimes` is still called. `/api/v1/map/stops` was replaced+ * by the baked `transit_stops` basemap layer (stops are static data) and+ * `/api/v1/plan` by the on-device RAPTOR planner, so their DTOs are gone.  */ -/** A transit stop drawn on the map and tapped to open its departure board. */+/**+ * A transit stop drawn on the map and tapped to open its departure board.+ *+ * [id] is the MOTIS/Transitous stop id baked into the `transit_stops` tile layer,+ * which is what the realtime board queries. A stop from a feed whose Transitous+ * source name the build did not know has none and falls back to its name, so the+ * offline board still opens but no live delays arrive.+ */ data class TransitStop(     val id: String,     val name: String,@@ -53,15 +64,6 @@ data class Departure(  // --- MOTIS v1 wire DTOs ---------------------------------------------------- -/** Response of `GET /api/v1/map/stops` — the stops within a viewport box. */-@Serializable-data class MotisMapStop(-    val id: String,-    val name: String = "",-    val lat: Double,-    val lon: Double,-)- /** Response of `GET /api/v1/stoptimes` — the live board for one stop. */ @Serializable data class MotisStoptimes(
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 591b31bb42..3d0580abef 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -79,7 +79,6 @@ import com.vayunmathur.maps.util.MapsSearchViewModel import com.vayunmathur.maps.util.PoiIndex import com.vayunmathur.maps.util.SelectedFeatureViewModel import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.serialization.json.Json@@ -143,7 +142,6 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,      // Public transit (P10): nearby stops overlay + live departure board. Stops     // are only fetched/drawn while the Transit layer is on.-    val transitStops by transitViewModel.stops.collectAsState()     val selectedTransitStop by transitViewModel.selected.collectAsState()     val departuresState by transitViewModel.departures.collectAsState() @@ -164,25 +162,6 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,     // visible on cold start.     val camera = rememberCameraState(CameraPosition(target = Position(-122.4194, 37.7749), zoom = 14.0)) -    LaunchedEffect(camera.position, transitEnabled) {-        if (camera.position.zoom >= 11.0) {-            delay(300) // Debounce idle-driven overlay refresh-            val projection = camera.projection-            if (projection != null) {-                val bbox = projection.queryVisibleBoundingBox()-                // Ambient POIs (P29) are now rendered NATIVELY from the baked-                // `ma_pois` PMTiles source-layer (see MaPoisLayer in MyMapLayers),-                // so no per-viewport offline-index query is needed here. PoiIndex-                // is still used for offline SEARCH only.-                // Refresh nearby transit stops (P10) only while the layer is on-                // (VM debounces + caches; wide views clear the overlay).-                if (transitEnabled) {-                    transitViewModel.onViewport(bbox.north, bbox.east, bbox.south, bbox.west)-                }-            }-        }-    }-     // Offline POI SEARCH index (poi_index.bin / poi_names.bin, P27). Ambient POI     // rendering is now native from the baked `ma_pois` PMTiles source-layer (see     // MaPoisLayer), so this index is only used to answer offline search queries.@@ -576,7 +555,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                             ClickResult.Pass                         }                 ) {-                        MyMapLayers(selectedFeature, route?.get(selectedRouteType), json, userPosition, userBearing, navProgress, searchResults, savedPins, parkingSpot, transitStops, familyMembers, trafficEnabled, satelliteEnabled, safetyEnabled, transitEnabled, poiFilterTypes = selectedCategory?.types)+                        MyMapLayers(selectedFeature, route?.get(selectedRouteType), json, userPosition, userBearing, navProgress, searchResults, savedPins, parkingSpot, familyMembers, trafficEnabled, satelliteEnabled, safetyEnabled, transitEnabled, poiFilterTypes = selectedCategory?.types)                     }                 } 
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 a7457b6c62..70046c2f3c 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt@@ -59,7 +59,6 @@ fun MyMapLayers(     searchResults: List<SearchResult> = emptyList(),     savedPlaces: List<com.vayunmathur.maps.data.SavedPlace> = emptyList(),     parkingSpot: com.vayunmathur.maps.data.ParkingSpot? = null,-    transitStops: List<com.vayunmathur.maps.data.transit.TransitStop> = emptyList(),     familyMembers: List<com.vayunmathur.maps.ipc.FamilyMember> = emptyList(),     trafficEnabled: Boolean = true,     satelliteEnabled: Boolean = false,@@ -165,10 +164,12 @@ fun MyMapLayers(         // Parking pin (P9). Tap → parking sheet (handled in MapPage.onMapClick).         ParkingLayer(parkingSpot) -        // Nearby transit stops (P10). Shown only when the Transit layer is on;-        // tap a stop → live departure board (handled in MapPage.onMapClick).         if (transitEnabled) {-            TransitStopsLayer(transitStops)+            // Baked GTFS stop pins (P10). Shown only when the Transit layer is on;+            // tap a stop → live departure board (handled in MapPage.onMapClick).+            // Same shared source as the admin/POI overlays — a second VectorSource+            // on the same PMTiles triggers a directory parse error.+            TransitStopsLayer(adminSource)         }          // Posted-speed-limit probe overlay (Decision D4). Invisible; queried
maps/src/main/java/com/vayunmathur/maps/ui/TransitStopsLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/TransitStopsLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/TransitStopsLayer.ktindex 9ea4313a91..e3b41be526 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/TransitStopsLayer.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/TransitStopsLayer.kt@@ -1,11 +1,7 @@ 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@@ -13,112 +9,131 @@ import androidx.compose.ui.unit.dp import com.vayunmathur.maps.data.Feature1 import com.vayunmathur.maps.data.string import com.vayunmathur.maps.data.transit.TransitStop-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.case import org.maplibre.compose.expressions.dsl.const+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.switch import org.maplibre.compose.expressions.dsl.zoom+import org.maplibre.compose.expressions.value.IntValue 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.sources.VectorSource 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 in MapPage.onMapClick so a tapped transit stop  *  opens its departure board. */ const val TRANSIT_STOP_LAYER_ID = "transit-stop-pins" private const val TRANSIT_STOP_DOT_LAYER_ID = "transit-stop-dots"-private const val TRANSIT_STOP_SOURCE_ID = "transit-stop-geojson"++/**+ * Baked GTFS stop layer. Placement, name, `motis_id` and `route_type` come from+ * the `transit_stops` source-layer in the v5 basemap PMTiles, written by+ * `scripts/maps/build_transit_stops_layer.sh`.+ *+ * This replaced a per-viewport `GET /api/v1/map/stops` fetch. Stops are static+ * data, so a network round-trip on every camera idle bought nothing, and the baked+ * `motis_id` means the realtime `/stoptimes` overlay still has an id to ask about+ * without that endpoint.+ */+object TransitStopsSource {+    const val SOURCE_LAYER: String = "transit_stops"+}  /** Transit teal so stops read distinctly from Google POIs (category colours),  *  saved pins (blue) and search results (red). */ private val TRANSIT_STOP_COLOR = Color(0xFF00897B) +/** Rail-like modes get a distinct colour from buses, so a subway entrance is+ *  visually separable from the bus stop outside it. GTFS route types: 0 tram,+ *  1 subway, 2 rail, 3 bus, 4 ferry. */+private val TRANSIT_RAIL_COLOR = Color(0xFF3949AB)+private val TRANSIT_FERRY_COLOR = Color(0xFF0277BD)+ /**- * Nearby-transit-stops overlay (P10): a [GeoJsonSource] fed from the viewport- * Transitous fetch plus a [CircleLayer] dot and a [SymbolLayer] glyph on top,- * ported to maplibre-compose declarative layers exactly like [GooglePoiLayer] /- * [SavedPlacesLayer]. Mounted only when the Transit layer toggle is on (see- * [MyMapLayers]); a tap → the [DeparturesSheet] via [toTransitStop].+ * Draw the `transit_stops` source-layer: a [CircleLayer] dot with a [SymbolLayer]+ * glyph on top, from z11 up. Takes the SAME shared [VectorSource] the admin and+ * POI overlays use — a second source on the same PMTiles triggers a directory+ * parse error (see the note at [MaPoisLayer]).+ *+ * The marker is a runtime Canvas bitmap rather than a sprite asset, so it renders+ * even while the style's remote glyphs 404; [MaPoisLayer] does the same.+ *+ * Mounted only when the Transit layer toggle is on (see [MyMapLayers]); a tap →+ * the [DeparturesSheet] via [toTransitStop].  */ @Composable @MaplibreComposable-fun TransitStopsLayer(stops: List<TransitStop>) {+fun TransitStopsLayer(source: VectorSource) {     val marker = remember { generateTransitMarkerBitmap() }-    var source by remember { mutableStateOf<GeoJsonSource?>(null) } -    LaunchedEffect(Unit) {-        source = GeoJsonSource(-            TRANSIT_STOP_SOURCE_ID,-            GeoJsonData.Features(FeatureCollection(emptyList<Feature1>())),-            GeoJsonOptions(),-        )-    }+    // Colour by mode. `switch` over the numeric route_type, as MyMapLayers does+    // for its own data-driven paint.+    val dotColor = switch(+        feature["route_type"].cast<IntValue>(),+        case(0, const(TRANSIT_RAIL_COLOR)),+        case(1, const(TRANSIT_RAIL_COLOR)),+        case(2, const(TRANSIT_RAIL_COLOR)),+        case(4, const(TRANSIT_FERRY_COLOR)),+        fallback = const(TRANSIT_STOP_COLOR),+    ) -    source?.let { src ->-        LaunchedEffect(stops) {-            src.setData(GeoJsonData.Features(FeatureCollection(stops.map { it.toFeature() })))-        }+    CircleLayer(+        TRANSIT_STOP_DOT_LAYER_ID,+        source,+        sourceLayer = TransitStopsSource.SOURCE_LAYER,+        minZoom = 11f,+        color = dotColor,+        radius = interpolate(+            linear(), zoom(),+            12 to const(4.dp),+            15 to const(6.dp),+            18 to const(8.dp),+        ),+        strokeColor = const(Color.White),+        strokeWidth = const(1.5.dp),+    ) -        CircleLayer(-            TRANSIT_STOP_DOT_LAYER_ID,-            src,-            color = const(TRANSIT_STOP_COLOR),-            radius = interpolate(-                linear(), zoom(),-                12 to const(4.dp),-                15 to const(6.dp),-                18 to const(8.dp),-            ),-            strokeColor = const(Color.White),-            strokeWidth = const(1.5.dp),-        )--        SymbolLayer(-            TRANSIT_STOP_LAYER_ID,-            src,-            iconImage = image(marker),-            iconSize = interpolate(-                linear(), zoom(),-                12 to const(0.35f),-                15 to const(0.5f),-                18 to const(0.65f),-            ),-        )-    }+    SymbolLayer(+        TRANSIT_STOP_LAYER_ID,+        source,+        sourceLayer = TransitStopsSource.SOURCE_LAYER,+        minZoom = 11f,+        iconImage = image(marker),+        iconSize = interpolate(+            linear(), zoom(),+            12 to const(0.35f),+            15 to const(0.5f),+            18 to const(0.65f),+        ),+    ) } -/** Rebuild a stop as a GeoJSON point feature; id/name/lat/lon ride along so- *  onMapClick can open the board for it. */-private fun TransitStop.toFeature(): Feature1 = Feature1(-    Point(Position(lon, lat)),-    JsonObject(-        mapOf(-            "id" to JsonPrimitive(id),-            "name" to JsonPrimitive(name),-            "lat" to JsonPrimitive(lat),-            "lng" to JsonPrimitive(lon),-        )-    ),-)--/** Convert a hit-tested transit-stop feature back into a [TransitStop] so the- *  tap handler can open the departure board. */+/**+ * Convert a hit-tested transit-stop feature back into a [TransitStop] so the tap+ * handler can open the departure board.+ *+ * Coordinates come from the point geometry, not from properties: a baked tile+ * carries no `lat`/`lng` fields, only the geometry the tiler wrote. [TransitStop.id]+ * takes `motis_id`, which is what the realtime board queries; a stop from a feed+ * whose Transitous source name the build did not know has none, and falls back to+ * its name so the offline board still opens.+ */ fun Feature1.toTransitStop(): TransitStop? {     val props = properties ?: return null-    val id = props.string("id")?.ifBlank { null } ?: return null-    val name = props.string("name")?.ifBlank { null } ?: id-    val lat = props["lat"]?.jsonPrimitive?.doubleOrNull ?: return null-    val lng = props["lng"]?.jsonPrimitive?.doubleOrNull ?: return null-    return TransitStop(id, name, lat, lng)+    val position = (geometry as? Point)?.coordinates ?: return null+    val name = props.string("name")?.ifBlank { null }+    val motisId = props.string("motis_id")?.ifBlank { null }+    val id = motisId ?: name ?: return null+    return TransitStop(+        id = id,+        name = name ?: id,+        lat = position.latitude,+        lon = position.longitude,+    ) }  /** Draw the transit marker once: a white centre dot on the teal base circle so
maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.ktindex bffdc49826..41e8fca46a 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt@@ -8,6 +8,7 @@ import com.vayunmathur.library.util.ConnectivityMonitor import com.vayunmathur.maps.R import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.data.transit.Departure+import com.vayunmathur.maps.data.transit.TransitStop import com.vayunmathur.maps.data.transit.TransitousDataSource import java.io.File import java.io.OutputStream@@ -169,6 +170,23 @@ object OfflineRouter {             lat: Double,             lon: Double     ): String?++    /**+     * MOTIS/Transitous id of the stop nearest `(lat, lon)` in the baked v5 pack,+     * or null when the pack is absent, predates v5, doesn't cover the point, or+     * its feed's Transitous source name was unknown at build time.+     *+     * A purely local lookup. It exists because the departure board fetches its+     * realtime overlay before it knows which stop the board is for, so it has to+     * name the stop up front — and since `/api/v1/map/stops` is gone, there is no+     * longer any network way to turn a coordinate into a MOTIS id.+     */+    private external fun nearestStopMotisIdNative(+            basePath: String,+            feed: String,+            lat: Double,+            lon: Double+    ): String?     private external fun updateTrafficNative(             edgeIds: LongArray,             speeds: ByteArray,@@ -283,6 +301,15 @@ object OfflineRouter {             val depSecs: Int,             /** Arrival, seconds since feed-local midnight (0 when unknown). */             val arrSecs: Int,+            /**+             * MOTIS/Transitous id of the ride's board stop, baked into the v5+             * pack. Null on a walk/wait leg, on a pre-v5 pack, or when the feed's+             * Transitous source name was unknown at build time — in which case the+             * realtime overlay simply has nothing to ask about for this leg.+             */+            val boardStopId: String?,+            /** MOTIS/Transitous id of the ride's alight stop. See [boardStopId]. */+            val alightStopId: String?,     )      /** One offline scheduled departure from the baked `.transit` index. */@@ -475,38 +502,48 @@ object OfflineRouter {     }      /**-     * Board and alight coordinates of every ride in a planned journey. A ride-     * leg's geometry runs through its stops, so the first and last points are-     * exactly the two stops whose realtime we need.+     * Board and alight stops of every ride in a planned journey, as+     * `(position, MOTIS id)`.+     *+     * The id is baked into the v5 pack, which is what lets the overlay name a stop+     * to `/stoptimes` directly. A leg whose pack predates v5, or whose feed's+     * Transitous source name the build did not know, carries no id and is dropped:+     * without one there is no way to ask about it now that the `/map/stops`+     * proximity lookup is gone, and it simply stays schedule-only.      */-    private fun journeyStops(steps: Array<RawStep>): List<Position> =+    private fun journeyStops(steps: Array<RawStep>): List<Pair<Position, String>> =             steps.filter { it.isTransit && it.geometry.size >= 4 }                     .flatMap { s ->                         val g = s.geometry-                        listOf(-                                Position(g[0], g[1]),-                                Position(g[g.size - 2], g[g.size - 1]),+                        listOfNotNull(+                                s.boardStopId?.ifBlank { null }+                                        ?.let { Position(g[0], g[1]) to it },+                                s.alightStopId?.ifBlank { null }+                                        ?.let { Position(g[g.size - 2], g[g.size - 1]) to it },                         )                     }-                    .distinct()+                    .distinctBy { it.second }      /**      * Fetch MOTIS boards for [stops] concurrently and flatten them into an-     * [Overlay]. Returns [Overlay.EMPTY] when the device is offline — without-     * that gate every offline plan would pay a full HTTP timeout per stop before-     * `runCatching` swallowed it.+     * [Overlay]. Each stop is named by its baked MOTIS id, so this is one+     * `/stoptimes` call per stop with no proximity round-trip.+     *+     * Returns [Overlay.EMPTY] when the device is offline — without that gate every+     * offline plan would pay a full HTTP timeout per stop before `runCatching`+     * swallowed it.      */     private suspend fun realtimeOverlay(             context: Context,-            stops: List<Position>,+            stops: List<Pair<Position, String>>,             clock: TransitClock,     ): Overlay {         if (stops.isEmpty() || !ConnectivityMonitor.isOnline(context)) return Overlay.EMPTY         val boards = coroutineScope {-            stops.map { p ->+            stops.map { (p, motisId) ->                 async(Dispatchers.IO) {                     p to runCatching {-                        TransitousDataSource.departuresNear(p.latitude, p.longitude)+                        TransitousDataSource.departures(motisId)                     }.getOrDefault(emptyList())                 }             }.awaitAll()@@ -532,6 +569,37 @@ object OfflineRouter {         return Overlay(coords.toDoubleArray(), routes.toTypedArray(), times.toIntArray())     } +    /**+     * The stop nearest `(lat, lon)` from the baked `*.transit` packs, as a+     * [TransitStop] whose id is the MOTIS/Transitous id so the realtime board can+     * query it. Null when no pack covers the point.+     *+     * Reached from a tapped station POI, which carries no stop id of its own. This+     * is a purely local lookup — `/api/v1/map/stops`, which used to answer+     * "what stop is here", is gone.+     */+    suspend fun nearestStop(+            context: Context,+            lat: Double,+            lon: Double,+    ): TransitStop? = withContext(Dispatchers.Default) {+        if (!isInitialized) initialize(context)+        val base = basePath ?: return@withContext null+        val feeds = File(base)+                .listFiles { f -> f.isFile && f.name.endsWith(".transit") }+                ?.map { it.name.removeSuffix(".transit") }+                ?: emptyList()+        for (feed in feeds) {+            val id = runCatching {+                nearestStopMotisIdNative(base, feed, lat, lon)+            }.getOrNull()?.ifBlank { null } ?: continue+            // The board resolves its own stop from the coordinate, so the name is+            // only a label until it loads; the MOTIS id is the part that matters.+            return@withContext TransitStop(id = id, name = id, lat = lat, lon = lon)+        }+        null+    }+     /**      * Departure board from the baked `*.transit` index for the stop nearest      * `(lat,lon)`. Scheduled times come from the pack; when the device is online@@ -558,7 +626,25 @@ object OfflineRouter {             val clock = transitClock(                     runCatching { getFeedTimezoneNative(base, feed, lat, lon) }.getOrNull()             )-            val overlay = realtimeOverlay(context, listOf(Position(lon, lat)), clock)+            // The board is fetched before we know which stop it is for, so name the+            // stop up front from the pack. No pack id (pre-v5, or a feed whose+            // Transitous source name the build did not know) means no realtime, and+            // the board stays schedule-only.+            //+            // Only the nearest stop's board is fetched, even though the offline+            // board aggregates co-located platforms within 150 m. That is+            // deliberate: the Rust overlay matches a delay to a stop within 60 m,+            // tight enough that adjacent platforms don't collide, so a neighbouring+            // platform's realtime could not be attributed anyway without carrying+            // per-stop coordinates back out of the board.+            val motisId = runCatching {+                nearestStopMotisIdNative(base, feed, lat, lon)+            }.getOrNull()?.ifBlank { null }+            val overlay = if (motisId == null) {+                Overlay.EMPTY+            } else {+                realtimeOverlay(context, listOf(Position(lon, lat) to motisId), clock)+            }             val raw = try {                 getStopDeparturesNative(                         base, feed, lat, lon,
maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.ktindex aa1c317533..ad7103a290 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt@@ -9,36 +9,30 @@ import com.vayunmathur.maps.data.transit.TransitStop import com.vayunmathur.maps.data.transit.TransitousDataSource 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.asStateFlow import kotlinx.coroutines.flow.combine-import kotlinx.coroutines.flow.debounce-import kotlinx.coroutines.flow.distinctUntilChanged-import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn-import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext-import kotlin.math.abs  /**- * Drives the P10 public-transit UI: the nearby-stops overlay and the departure- * board (both online via [TransitousDataSource]).+ * Drives the P10 public-transit UI: the departure board for a tapped stop.  *- * Two independent flows:- *  - [stops] — a debounced, LRU-cached list of [TransitStop]s for the current- *    viewport (mirrors [GooglePoiMapViewModel]); wider-than-city views clear the- *    overlay since stops there are meaningless and dense.- *  - [departures] — the board for the [openStop]-selected stop, re-fetched on- *    [refresh]. The live countdown itself is computed client-side in the sheet- *    from each departure's epoch time, so no polling is needed here.+ * The stop *pins* are no longer this class's business — they render straight from+ * the baked `transit_stops` basemap layer (see+ * [com.vayunmathur.maps.ui.TransitStopsLayer]), since stops are static data and a+ * per-viewport fetch on every camera idle bought nothing.+ *+ * [departures] is the board for the [openStop]-selected stop, re-fetched on+ * [refresh]. The live countdown itself is computed client-side in the sheet from+ * each departure's epoch time, so no polling is needed here.  *  * All network is on [Dispatchers.IO], and is skipped entirely when  * [ConnectivityMonitor] reports no validated internet — otherwise every offline@@ -48,36 +42,6 @@ import kotlin.math.abs  */ class TransitStopsViewModel(application: Application) : AndroidViewModel(application) { -    private data class Bbox(val north: Double, val east: Double, val south: Double, val west: Double)--    // Rounded viewport box; null suppresses fetching (zoomed out / too wide).-    private val _bbox = MutableStateFlow<Bbox?>(null)--    @OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)-    val stops: StateFlow<List<TransitStop>> = _bbox-        .filterNotNull()-        .debounce(DEBOUNCE_MS)-        .distinctUntilChanged()-        .mapLatest { b ->-            if (!ConnectivityMonitor.isOnline(getApplication())) emptyList()-            else TransitousDataSource.stopsInBbox(b.south, b.west, b.north, b.east)-        }-        .flowOn(Dispatchers.IO)-        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())--    /**-     * Feed a camera-idle viewport (from `queryVisibleBoundingBox()`). Views-     * wider than [MAX_LAT_SPAN] clear the stops; otherwise the rounded box drives-     * the next fetch.-     */-    fun onViewport(north: Double, east: Double, south: Double, west: Double) {-        if (abs(north - south) > MAX_LAT_SPAN) {-            _bbox.value = null-            return-        }-        _bbox.value = Bbox(round3(north), round3(east), round3(south), round3(west))-    }-     // --- Departure board ---------------------------------------------------      private val _selected = MutableStateFlow<TransitStop?>(null)@@ -126,22 +90,20 @@ class TransitStopsViewModel(application: Application) : AndroidViewModel(applica     }      /**-     * Resolve the nearest Transitous stop to [lat],[lon] (a tapped station POI-     * carries no stop id) and open its board. Queries a small bbox and picks the-     * closest stop; no-op if none are found nearby.+     * Resolve the stop nearest [lat],[lon] and open its board. Reached from a+     * tapped `ma_pois` station POI, which carries no stop id of its own.+     *+     * Resolved from the baked `.transit` pack rather than over the network: the+     * pack already holds every stop's position and MOTIS id, so this needs no+     * connectivity and works for the same coverage the offline board does. No-op+     * when no pack covers the point.      */     fun openNearestStop(lat: Double, lon: Double) {         viewModelScope.launch {-            val d = 0.01 // ~1.1km search box around the tapped station-            val stops = withContext(Dispatchers.IO) {-                TransitousDataSource.stopsInBbox(lat - d, lon - d, lat + d, lon + d)-            }-            val nearest = stops.minByOrNull { s ->-                val dLat = s.lat - lat-                val dLon = s.lon - lon-                dLat * dLat + dLon * dLon+            val stop = withContext(Dispatchers.IO) {+                OfflineRouter.nearestStop(getApplication(), lat, lon)             } ?: return@launch-            openStop(nearest)+            openStop(stop)         }     } @@ -154,16 +116,6 @@ class TransitStopsViewModel(application: Application) : AndroidViewModel(applica     fun refresh() {         if (_selected.value != null) _refreshTick.value += 1     }--    private fun round3(v: Double): Double = Math.round(v * 1000.0) / 1000.0--    private companion object {-        const val DEBOUNCE_MS = 500L--        // ~9 km of latitude — transit stops are dense, so keep the fetch to a-        // tighter zoom than the Google-POI overlay.-        const val MAX_LAT_SPAN = 0.08-    } }  /** UI state for the departure board. */
maps/src/main/rust/src/lib.rs
diff --git a/maps/src/main/rust/src/lib.rs b/maps/src/main/rust/src/lib.rsindex ded599e4cb..c5a31c8121 100644--- a/maps/src/main/rust/src/lib.rs+++ b/maps/src/main/rust/src/lib.rs@@ -201,7 +201,9 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_findRouteNat         Ok(c) => c,         Err(_) => return null,     };-    let ctor = "(ILjava/lang/String;JJ[DDZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;I[ILjava/lang/String;III)V";+    // MUST match the descriptor at the transit call site below: one ctor, two+    // callers. The trailing two Strings are the ride's MOTIS board/alight ids.+    let ctor = "(ILjava/lang/String;JJ[DDZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;I[ILjava/lang/String;IIILjava/lang/String;Ljava/lang/String;)V";      let array = match env.new_object_array(steps.len() as i32, &class, JObject::null()) {         Ok(a) => a,@@ -258,6 +260,9 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_findRouteNat                 JValue::Int(0),                 JValue::Int(0),                 JValue::Int(0),+                // No MOTIS stop ids on a road-graph step.+                JValue::Object(&JObject::null()),+                JValue::Object(&JObject::null()),             ],         ) {             Ok(o) => o,@@ -537,7 +542,9 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_findTransitR         Ok(c) => c,         Err(_) => return null,     };-    let ctor = "(ILjava/lang/String;JJ[DDZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;I[ILjava/lang/String;III)V";+    // MUST match the descriptor at the driving call site above: one ctor, two+    // callers. The trailing two Strings are the ride's MOTIS board/alight ids.+    let ctor = "(ILjava/lang/String;JJ[DDZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;I[ILjava/lang/String;IIILjava/lang/String;Ljava/lang/String;)V";     let array = match env.new_object_array(legs.len() as i32, &class, JObject::null()) {         Ok(a) => a,         Err(_) => return null,@@ -581,6 +588,18 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_findTransitR         } else {             JObject::null()         };+        // Only a ride carries realtime, so only a ride carries stop ids. Empty on+        // a pre-v5 pack, which leaves the overlay with nothing to ask about.+        let jboard = if is_transit {+            opt_str(&mut env, &leg.board_stop_motis_id)+        } else {+            JObject::null()+        };+        let jalight = if is_transit {+            opt_str(&mut env, &leg.alight_stop_motis_id)+        } else {+            JObject::null()+        };          // Every leg's duration comes from RAPTOR's own times. A walk leg's         // `dist_m` may have been redrawn along the road graph, which is longer@@ -621,6 +640,8 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_findTransitR                 JValue::Int(leg.route_color as i32),                 JValue::Int(leg.dep_secs as i32),                 JValue::Int(leg.arr_secs as i32),+                JValue::Object(&jboard),+                JValue::Object(&jalight),             ],         ) {             Ok(o) => o,@@ -809,6 +830,55 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getFeedTimez     } } +// ---------------------------------------------------------------------------+// JNI: nearestStopMotisIdNative (MOTIS id of the stop nearest a coordinate)+// ---------------------------------------------------------------------------++/// MOTIS/Transitous stop id (e.g. `us-ca-SF-bayarea_901201`) of the stop nearest+/// `(lat, lon)` in `<base_path>/<feed>.transit`, from the v5 `FEED_MOTIS_PREFIX` ++/// `STOP_GTFS_ID` sections. Returns null when the pack is absent, predates v5,+/// doesn't cover the point, or its feed's Transitous source name was unknown at+/// build time.+///+/// Exists because the departure board fetches its realtime overlay *before* it+/// knows which stop the board is for, so it needs to name the stop up front. A+/// local lookup, no network — which is the whole point of baking the id.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_nearestStopMotisIdNative<+    'local,+>(+    mut env: JNIEnv<'local>,+    _thiz: JObject<'local>,+    base_path: JString<'local>,+    feed: JString<'local>,+    lat: jdouble,+    lon: jdouble,+) -> jstring {+    let null = std::ptr::null_mut();+    let base: String = match env.get_string(&base_path) {+        Ok(s) => s.into(),+        Err(_) => return null,+    };+    let feed_name: String = match env.get_string(&feed) {+        Ok(s) => s.into(),+        Err(_) => return null,+    };+    let index = match transit::TransitIndex::load(&base, &feed_name) {+        Some(i) => i,+        None => return null,+    };+    if !index.covers(lat, lon) {+        return null;+    }+    match index.nearest_stop_motis_id(lat, lon) {+        Some(id) => match env.new_string(&id) {+            Ok(s) => s.into_raw(),+            Err(_) => null,+        },+        None => null,+    }+}+ // --------------------------------------------------------------------------- // JNI: updateTrafficNative // ---------------------------------------------------------------------------@@ -1005,6 +1075,8 @@ mod tests {             stop_count: 0,             dist_m,             coords,+            board_stop_motis_id: String::new(),+            alight_stop_motis_id: String::new(),         }     } 
maps/src/main/rust/src/transit.rs
diff --git a/maps/src/main/rust/src/transit.rs b/maps/src/main/rust/src/transit.rsindex 0540c28d10..23bf53d29e 100644--- a/maps/src/main/rust/src/transit.rs+++ b/maps/src/main/rust/src/transit.rs@@ -183,6 +183,12 @@ pub struct TransitLeg {     pub dist_m: f64,     /// Flat `[lon, lat, lon, lat, ...]` polyline through the leg's stops.     pub coords: Vec<f64>,+    /// MOTIS/Transitous ids of the ride's board and alight stops (v5 packs only;+    /// empty otherwise, and empty for non-ride legs). The realtime overlay asks+    /// `/stoptimes` about these directly, which is what removed the old+    /// coordinate-to-id round trip through `/map/stops`.+    pub board_stop_motis_id: String,+    pub alight_stop_motis_id: String, }  /// What keeps an index's bytes alive: an mmap of the pack file in production, or@@ -718,6 +724,15 @@ impl TransitIndex {         None     } +    /// MOTIS id of the stop nearest `(lat, lon)`, for a caller that must name a+    /// stop before it knows which one it wants — the departure board fetches its+    /// realtime overlay before running the board query. Local lookup, no network.+    pub fn nearest_stop_motis_id(&self, lat: f64, lon: f64) -> Option<String> {+        const NEAREST_MAX_M: f64 = 400.0;+        let (stop, _) = self.nearest_stop(lat, lon, NEAREST_MAX_M)?;+        self.motis_stop_id(stop)+    }+     /// IANA timezone of the feed covering `(lat, lon)`, resolved via the nearest     /// stop and one of the routes serving it. Stops carry no `feed_idx` — only     /// `RouteRec` does — so the route hop is required. Empty when nothing is@@ -1169,6 +1184,9 @@ pub fn plan(                 stop_count: 0,                 dist_m: access_d,                 coords: vec![from_lon, from_lat, flon, flat],+                // Walk legs carry no realtime, so they need no MOTIS ids.+                board_stop_motis_id: String::new(),+                alight_stop_motis_id: String::new(),             },         );     }@@ -1188,6 +1206,8 @@ pub fn plan(             stop_count: 0,             dist_m: egress_d,             coords: vec![elon, elat, to_lon, to_lat],+            board_stop_motis_id: String::new(),+            alight_stop_motis_id: String::new(),         });     } @@ -1223,6 +1243,11 @@ fn insert_wait_legs(legs: Vec<TransitLeg>, dep_secs: u32) -> Vec<TransitLeg> {                 stop_count: 0,                 dist_m: 0.0,                 coords: Vec::new(),+                // A wait happens at the following ride's board stop, whose id that+                // ride already carries; duplicating it here would double the+                // overlay's fetch for one stop.+                board_stop_motis_id: String::new(),+                alight_stop_motis_id: String::new(),             });         }         out.push(leg);@@ -1544,6 +1569,8 @@ fn make_transit_leg(         stop_count: (count - 1).max(0),         dist_m: dist,         coords,+        board_stop_motis_id: idx.motis_stop_id(board_stop).unwrap_or_default(),+        alight_stop_motis_id: idx.motis_stop_id(alight_stop).unwrap_or_default(),     } } @@ -1569,6 +1596,8 @@ fn make_walk_leg(         stop_count: 0,         dist_m: dist_m(flat, flon, tlat, tlon),         coords: vec![flon, flat, tlon, tlat],+        board_stop_motis_id: String::new(),+        alight_stop_motis_id: String::new(),     } }