maps: only genuinely different alternative routes (#nav)
- Commit
e7e99f6fc73b412f06d0997311c27102b0f12070- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 20:06 UTC (19 days ago)
- Parents
88dfa8c
Audit of what existed: the native road router (findRouteNative) and the RAPTOR transit planner each return exactly one route per mode, so the only alternatives the sheet showed were the four travel modes themselves. There was no within-mode candidate list and no duplicate filtering at all. This adds bounded candidate generation plus diversity gating: - Generation (one extra plan per mode, primary unchanged): road modes route a via-detour second plan (direct midpoint pushed perpendicular by max(400 m, 20% of the direct distance)); transit plans RAPTOR again 15 minutes later (a departure-offset entry point on the transit planner); multi-waypoint routes generate nothing, so user legs are never rewritten. - Gate (AlternativeRoutes, pure and unit-tested): road candidates sharing >= 0.70 of the primary's geometry by length (30 m match tolerance, midpoint-to-polyline) are the same corridor with a one-street swap and are rejected. Transit candidates are compared by leg signature (boarded line + board/alight stops) and by boarded-service sequence: equal/subset/truncated signatures and same-line re-cuts (early alight + longer walk, next bus on the same line) are rejected, as is any journey over 0.45 walking share by distance. Candidates keep their generated (ETA) order and the primary is always kept, so shown ordering and the primary choice are unchanged; when nothing passes, exactly one route is shown. - UI: the VM plans gated alternatives for the visible mode only; RouteSheet shows an Other routes section (duration, distance, transit lines) and tapping one swaps it in as the shown route for the sheet and the map overlay, tapping again returns to the primary. Compact and wide share the scope. Current vs new behaviour: before, one route per mode and no alternatives within a mode. Now a second route appears only when it is corridor-different (road) or a genuinely different service sequence (transit); same-corridor and same-ride variants never appear, and the common no-diverse-route case shows exactly the primary as before. Tests: AlternativeRoutesTest on synthetic routes proves the early-alight and same-line transit rejections, the distinct-line acceptance, the walk-heavy rejection, the one-street-swap rejection, the distinct-corridor acceptance, the single-route case and ETA-order preservation. Verified: :maps:compileDevKotlin green; AlternativeRoutesTest passes; full suite run follows.
Diff
maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.ktindex 8374ccd4c0..63a12b8c20 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt@@ -101,6 +101,9 @@ fun BottomSheetContent( setSelectedRouteType: (RouteService.TravelMode) -> Unit, navState: NavigationSessionManager.NavState = NavigationSessionManager.NavState.Idle, onStartNavigation: ((String, RouteService.TravelMode) -> Unit)? = null,+ alternatives: List<RouteService.Route> = emptyList(),+ selectedAlternative: RouteService.Route? = null,+ onSelectAlternative: (RouteService.Route?) -> Unit = {}, ) { when (selectedFeature) { is SpecificFeature.Admin0Label ->@@ -137,7 +140,7 @@ fun BottomSheetContent( is SpecificFeature.Route -> { val currentRoute = route if (currentRoute != null) {- RouteSheet(selectedFeature, currentRoute, selectedRouteType, setSelectedRouteType, navState, panelState.userPosition, onStartNavigation = onStartNavigation)+ RouteSheet(selectedFeature, currentRoute, selectedRouteType, setSelectedRouteType, navState, panelState.userPosition, onStartNavigation = onStartNavigation, alternatives = alternatives, selectedAlternative = selectedAlternative, onSelectAlternative = onSelectAlternative) } else { // Routes arrive asynchronously and start out null, so this is the state right // after asking for directions. It used to render nothing at all, inside a sheet
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 19b802d26a..93ea3dd0e5 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -156,7 +156,16 @@ fun MapPage( // the route back (setLast), and routes plans that mode first. val activeRoutePlan = sheetStack.backStack.routePlan() val selectedRouteType = activeRoutePlan?.mode ?: RouteService.TravelMode.DRIVE- val route by viewModel.routes.collectAsState(null)+ val routesByMode by viewModel.routes.collectAsState(null)+ val alternatives by viewModel.alternatives.collectAsState()+ var selectedAlternative by remember { mutableStateOf<RouteService.Route?>(null) }+ LaunchedEffect(sheetStack.backStack.engineRoute()) { selectedAlternative = null }+ val route = remember(routesByMode, selectedAlternative, activeRoutePlan) {+ val base = routesByMode ?: return@remember null+ val alt = selectedAlternative ?: return@remember base+ val mode = activeRoutePlan?.mode ?: return@remember base+ base.toMutableMap().apply { this[mode] = alt }+ } // Collected here (rather than inside the sheet) so the inner place sheet's // contentKey can name them: the tab switch and the late-arriving reviews // each change the sheet's content height, and without them in the key the@@ -359,6 +368,9 @@ fun MapPage( wide = wide, sheetStack = sheetStack, pushDepartures = ::pushDepartures,+ alternatives = alternatives,+ selectedAlternative = selectedAlternative,+ onSelectAlternative = { selectedAlternative = it }, onStartNavigating = onStartNavigating, onExitNavigating = { stopNavigation(context)
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 1f0f46824a..cb023a3691 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.kt@@ -145,6 +145,9 @@ internal class MapPageScope( val sheetStack: SheetBackStack<SheetRoute> = SheetBackStack(arrayOf(SheetRoute.Browse)), val pushDepartures: (Double, Double, String?) -> Unit = { _, _, _ -> }, val onStartNavigating: (String, RouteService.TravelMode) -> Unit = { _, _ -> },+ val alternatives: List<RouteService.Route> = emptyList(),+ val selectedAlternative: RouteService.Route? = null,+ val onSelectAlternative: (RouteService.Route?) -> Unit = {}, val onExitNavigating: () -> Unit = {}, ) { /** Top of the sheet stack: which sheet/panel/dialog is showing. */
maps/src/main/java/com/vayunmathur/maps/ui/MapSheets.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapSheets.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapSheets.ktindex ab54bd9f78..13cdd48f55 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapSheets.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapSheets.kt@@ -93,6 +93,9 @@ internal fun MapPageScope.MapSheets( setSelectedRouteType = onRouteMode, navState = navState, onStartNavigation = onStartNavigating,+ alternatives = alternatives,+ selectedAlternative = selectedAlternative,+ onSelectAlternative = onSelectAlternative, ) } }
maps/src/main/java/com/vayunmathur/maps/ui/MapSidePanel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapSidePanel.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapSidePanel.ktindex 904dacd463..e4ab5aa6b5 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapSidePanel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapSidePanel.kt@@ -52,6 +52,9 @@ fun MapSidePanel( navState: NavigationSessionManager.NavState, onClosePanel: () -> Unit, onStartNavigation: ((String, RouteService.TravelMode) -> Unit)? = null,+ alternatives: List<RouteService.Route> = emptyList(),+ selectedAlternative: RouteService.Route? = null,+ onSelectAlternative: (RouteService.Route?) -> Unit = {}, modifier: Modifier = Modifier, ) { Surface(modifier = modifier) {@@ -93,6 +96,9 @@ fun MapSidePanel( onSelectedRouteType, navState, onStartNavigation = onStartNavigation,+ alternatives = alternatives,+ selectedAlternative = selectedAlternative,+ onSelectAlternative = onSelectAlternative, ) } }
maps/src/main/java/com/vayunmathur/maps/ui/MapWideHost.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapWideHost.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapWideHost.ktindex 9f616813d4..6e3cd36ba2 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapWideHost.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapWideHost.kt@@ -91,6 +91,9 @@ internal fun MapPageScope.MapWideHost( navState = navState, onClosePanel = { sheetStack.popSheet() }, onStartNavigation = onStartNavigating,+ alternatives = alternatives,+ selectedAlternative = selectedAlternative,+ onSelectAlternative = onSelectAlternative, modifier = modifier, ) }@@ -110,6 +113,9 @@ internal fun MapPageScope.MapWideHost( navState = navState, onClosePanel = { sheetStack.reset(SheetRoute.Browse) }, onStartNavigation = onStartNavigating,+ alternatives = alternatives,+ selectedAlternative = selectedAlternative,+ onSelectAlternative = onSelectAlternative, modifier = modifier, ) }
maps/src/main/java/com/vayunmathur/maps/ui/RouteSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/RouteSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/RouteSheet.ktindex 38e02c41ac..5c349da165 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/RouteSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/RouteSheet.kt@@ -50,6 +50,7 @@ import com.vayunmathur.maps.util.formatDistance import com.vayunmathur.maps.util.formatDuration import com.vayunmathur.maps.util.formatEta import androidx.compose.foundation.layout.size+import androidx.compose.foundation.clickable /** * The directions panel: one segment per travel mode, then the turn-by-turn step list.@@ -73,6 +74,9 @@ fun RouteSheet( userPosition: GeoPoint? = null, modifier: Modifier = Modifier, onStartNavigation: ((String, RouteService.TravelMode) -> Unit)? = null,+ alternatives: List<RouteService.Route> = emptyList(),+ selectedAlternative: RouteService.Route? = null,+ onSelectAlternative: (RouteService.Route?) -> Unit = {}, ) { val context = LocalContext.current @@ -183,6 +187,14 @@ fun RouteSheet( return@Column } + if (alternatives.isNotEmpty()) {+ AlternativesSection(+ alternatives = alternatives,+ selected = selectedAlternative,+ onSelect = onSelectAlternative,+ )+ }+ val routeForMode = route[selectedRouteType] if (routeForMode != null) { if (routeForMode !is RouteService.EmptyRoute) {@@ -336,3 +348,45 @@ internal fun transitSupportingText(details: RouteService.API.TransitDetails): St else -> headsign ?: stops ?: "" } }++/**+ * Genuinely different alternatives for the shown mode (already gated by+ * [com.vayunmathur.maps.util.AlternativeRoutes]): duration/distance, and+ * for transit the boarded lines, so the difference is visible rather than+ * asserted. Tapping one swaps it in as the shown route; tapping the+ * selected one again returns to the primary.+ */+@Composable+private fun AlternativesSection(+ alternatives: List<RouteService.Route>,+ selected: RouteService.Route?,+ onSelect: (RouteService.Route?) -> Unit,+) {+ val context = LocalContext.current+ Column(Modifier.padding(horizontal = Spacing.lg, vertical = Spacing.sm)) {+ Text(+ stringResource(R.string.alternative_routes_title),+ style = MaterialTheme.typography.titleSmall,+ )+ alternatives.forEach { alternative ->+ val lines = alternative.step.mapNotNull {+ it.transitDetails?.transitLine?.let { line -> line.nameShort ?: line.name }+ }.distinct()+ Card(+ modifier = Modifier.fillMaxWidth().padding(top = Spacing.sm)+ .clickable { onSelect(if (selected == alternative) null else alternative) },+ ) {+ ListItem({+ Text(+ listOfNotNull(+ formatDuration(context, alternative.duration),+ formatDistance(alternative.distanceMeters),+ lines.joinToString(" · ").takeIf { it.isNotBlank() },+ stringResource(R.string.alternative_selected).takeIf { selected == alternative },+ ).joinToString(" · "),+ )+ })+ }+ }+ }+}
maps/src/main/java/com/vayunmathur/maps/util/AlternativeRoutes.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/AlternativeRoutes.kt b/maps/src/main/java/com/vayunmathur/maps/util/AlternativeRoutes.ktnew file mode 100644index 0000000000..ba5d162cf5--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/AlternativeRoutes.kt@@ -0,0 +1,189 @@+package com.vayunmathur.maps.util++import com.vayunmathur.library.map.GeoPoint+import kotlin.math.asin+import kotlin.math.cos+import kotlin.math.min+import kotlin.math.pow+import kotlin.math.sin+import kotlin.math.sqrt++/**+ * Diversity gating for alternative routes.+ *+ * Audit (2026-11): the native road router (`findRouteNative`) and the+ * RAPTOR transit planner each return exactly **one** route per mode, so+ * the only "alternatives" the sheet showed were the four travel modes —+ * there was no within-mode candidate list and no duplicate filtering at+ * all. Candidates are now generated on top of those single-route+ * planners (a via-detour second road plan; a later-departure second+ * RAPTOR plan) and every candidate must pass this gate before it is+ * shown. If nothing passes, exactly one route — the primary — is shown.+ *+ * Thresholds, tuned to what the planners actually produce:+ * - [MAX_SHARED_GEOMETRY_RATIO]: road alternatives that share 70% or+ * more of the primary's geometry (by length) are the same corridor+ * with a one-street swap, not an alternative.+ * - [MAX_WALK_SHARE]: a transit journey that is more than 45% walking+ * by distance is a walk with a ride in it, not a transit alternative.+ * - Transit legs are compared by **signature** (the boarded line ++ * board/alight stops of each ride leg): an alternative whose leg+ * sequence equals, or is a subset/truncation of, an already-shown+ * journey's is the same ride taken less far (early alight + longer+ * walk), however it is re-padded.+ *+ * The primary is always kept, and candidates keep their input order+ * (fastest first as generated), so ETA ordering among shown routes+ * and the primary choice are never degraded by gating.+ */+object AlternativeRoutes {++ /** Above this shared-geometry ratio a road candidate is a near-duplicate. */+ const val MAX_SHARED_GEOMETRY_RATIO = 0.70++ /** Above this walking share a transit candidate is not a transit route. */+ const val MAX_WALK_SHARE = 0.45++ /** Geometry match tolerance (m) for the shared-length measurement. */+ private const val MATCH_TOLERANCE_M = 30.0++ /** One boarded ride of a transit journey, for signature comparison. */+ data class TransitLegKey(val line: String, val board: String, val alight: String)++ /** The boarded-service sequence of [route]; empty for non-transit routes. */+ fun transitSignature(route: RouteService.Route): List<TransitLegKey> =+ route.step.mapNotNull { step ->+ val details = step.transitDetails ?: return@mapNotNull null+ TransitLegKey(+ line = details.transitLine.nameShort ?: details.transitLine.name,+ board = details.stopDetails.departureStop.name,+ alight = details.stopDetails.arrivalStop.name,+ )+ }++ /** Walking share of [route] by distance (0 when the route is empty). */+ fun walkShare(route: RouteService.Route): Double {+ if (route.distanceMeters <= 0.0) return 0.0+ val walk = route.step+ .filter { it.travelMode == RouteService.TravelMode.WALK }+ .sumOf { it.distanceMeters }+ return walk / route.distanceMeters+ }++ /**+ * Shared length of [candidate] with [primary], as a ratio of the+ * primary's length: each candidate segment whose midpoint lies within+ * [MATCH_TOLERANCE_M] of the primary's polyline counts as shared.+ */+ fun sharedGeometryRatio(primary: RouteService.Route, candidate: RouteService.Route): Double {+ val primaryLength = polylineLength(primary.polyline)+ if (primaryLength <= 0.0 || candidate.polyline.size < 2) return 0.0+ var shared = 0.0+ for (i in 0 until candidate.polyline.size - 1) {+ val a = candidate.polyline[i]+ val b = candidate.polyline[i + 1]+ val mid = GeoPoint((a.longitude + b.longitude) / 2, (a.latitude + b.latitude) / 2)+ if (distanceToPolylineM(mid, primary.polyline) <= MATCH_TOLERANCE_M) {+ shared += haversineM(a, b)+ }+ }+ return min(1.0, shared / primaryLength)+ }++ /**+ * The genuinely different alternatives to [primary] among+ * [candidates], in input order. [transit] selects the transit gates+ * (signature + walk share); otherwise the corridor-overlap gate+ * applies, which also covers walk/cycle candidates.+ */+ fun diverseAlternatives(+ primary: RouteService.Route,+ candidates: List<RouteService.Route>,+ transit: Boolean,+ ): List<RouteService.Route> {+ val accepted = mutableListOf(primary)+ val out = mutableListOf<RouteService.Route>()+ for (candidate in candidates) {+ if (candidate === primary) continue+ val passes = if (transit) {+ transitPasses(candidate, accepted)+ } else {+ accepted.all { sharedGeometryRatio(it, candidate) < MAX_SHARED_GEOMETRY_RATIO }+ }+ if (passes) {+ accepted.add(candidate)+ out.add(candidate)+ }+ }+ return out+ }++ private fun transitPasses(+ candidate: RouteService.Route,+ accepted: List<RouteService.Route>,+ ): Boolean {+ val signature = transitSignature(candidate)+ if (signature.isEmpty()) return false+ if (walkShare(candidate) > MAX_WALK_SHARE) return false+ return accepted.none { other ->+ val otherSignature = transitSignature(other)+ // Same boarded-service sequence is the same ride, however the+ // stops are re-cut (early alight, board one stop later): the+ // leg-key subset check below catches truncations, and this+ // line-sequence check catches the same services with+ // different board/alight stops.+ val lines = signature.map { it.line }+ val otherLines = otherSignature.map { it.line }+ otherSignature == signature || isSubsetOrTruncation(signature, otherSignature) ||+ lines == otherLines || lines.toSet().all { it in otherLines.toSet() }+ }+ }++ /** True when [a]'s leg set is contained in [b]'s, or [a] is a prefix of [b]. */+ private fun isSubsetOrTruncation(a: List<TransitLegKey>, b: List<TransitLegKey>): Boolean {+ if (a.size <= b.size && b.subList(0, a.size) == a) return true+ return a.toSet().all { it in b.toSet() }+ }++ private fun polylineLength(points: List<GeoPoint>): Double {+ var total = 0.0+ for (i in 0 until points.size - 1) total += haversineM(points[i], points[i + 1])+ return total+ }++ private fun distanceToPolylineM(point: GeoPoint, line: List<GeoPoint>): Double {+ var best = Double.MAX_VALUE+ for (i in 0 until line.size - 1) {+ best = min(best, distanceToSegmentM(point, line[i], line[i + 1]))+ }+ return best+ }++ /** Point-to-segment distance in metres, equirectangular around [p]. */+ private fun distanceToSegmentM(p: GeoPoint, a: GeoPoint, b: GeoPoint): Double {+ val kx = 111_320.0 * cos(Math.toRadians(p.latitude))+ val ky = 110_540.0+ val px = 0.0+ val py = 0.0+ val ax = (a.longitude - p.longitude) * kx+ val ay = (a.latitude - p.latitude) * ky+ val bx = (b.longitude - p.longitude) * kx+ val by = (b.latitude - p.latitude) * ky+ val dx = bx - ax+ val dy = by - ay+ val lenSq = dx * dx + dy * dy+ val t = if (lenSq == 0.0) 0.0 else (((px - ax) * dx + (py - ay) * dy) / lenSq).coerceIn(0.0, 1.0)+ val cx = ax + t * dx+ val cy = ay + t * dy+ return sqrt((px - cx).pow(2) + (py - cy).pow(2))+ }++ private fun haversineM(a: GeoPoint, b: GeoPoint): Double {+ val r = 6_371_000.0+ val dLat = Math.toRadians(b.latitude - a.latitude)+ val dLon = Math.toRadians(b.longitude - a.longitude)+ val h = sin(dLat / 2).pow(2) ++ cos(Math.toRadians(a.latitude)) * cos(Math.toRadians(b.latitude)) * sin(dLon / 2).pow(2)+ return 2 * r * asin(min(1.0, sqrt(h)))+ }+}
maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterRoadRoutes.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterRoadRoutes.kt b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterRoadRoutes.ktindex 0b8db81a8d..19d85b8a4d 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterRoadRoutes.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterRoadRoutes.kt@@ -133,3 +133,67 @@ internal object OfflineRouterRoadRoutes { ) } }++/**+ * Primary plus genuinely different alternatives for a two-point route.+ *+ * Candidate generation is deliberately bounded — one extra plan per+ * mode, on top of the single-route native planners: a via-detour plan+ * (midpoint pushed perpendicular to the direct corridor) for road+ * modes, and a later-departure RAPTOR plan for transit. Every candidate+ * then has to pass [AlternativeRoutes.diverseAlternatives]; when none+ * does, the result is exactly the primary. Multi-waypoint routes get+ * no generated candidates (a via point would rewrite the user's legs).+ */+/** See [AlternativeRoutes] for the gating this feeds. */+internal suspend fun planWithAlternatives(+ context: android.content.Context,+ route: SpecificFeature.Route,+ userPosition: GeoPoint,+ mode: RouteService.TravelMode,+): List<RouteService.Route> {+ val primary = OfflineRouterRoadRoutes.getRouteForMode(context, route, userPosition, mode)+ ?: return emptyList()+ val positions = route.waypoints.map { it?.position ?: userPosition }+ if (positions.size != 2) return listOf(primary)+ val start = positions.first()+ val end = positions.last()+ val candidate = try {+ if (mode == RouteService.TravelMode.TRANSIT) {+ OfflineRouterTransit.getTransitRouteOffline(context, start, end, departureOffsetSecs = 900)+ } else {+ val via = viaPoint(start, end)+ val viaFeature = SpecificFeature.GenericPlace("via", null, null, null, via)+ OfflineRouterRoadRoutes.getRouteMulti(+ context,+ SpecificFeature.Route(listOf(route.waypoints.first(), viaFeature, route.waypoints.last())),+ userPosition,+ mode,+ )+ }+ } catch (_: Exception) {+ null+ }+ val candidates = listOfNotNull(candidate)+ return listOf(primary) + AlternativeRoutes.diverseAlternatives(+ primary, candidates, transit = mode == RouteService.TravelMode.TRANSIT,+ )+}++/**+ * The midpoint of start→end pushed perpendicular by the larger of+ * 400 m or 20% of the direct distance: far enough to force a different+ * corridor where one exists, near enough that the detour is a route a+ * person might actually take.+ */+private fun viaPoint(start: GeoPoint, end: GeoPoint): GeoPoint {+ val midLat = (start.latitude + end.latitude) / 2+ val midLon = (start.longitude + end.longitude) / 2+ val dLat = end.latitude - start.latitude+ val dLon = (end.longitude - start.longitude) * kotlin.math.cos(Math.toRadians(midLat))+ val len = kotlin.math.sqrt(dLat * dLat + dLon * dLon).coerceAtLeast(1e-9)+ val offsetDeg = maxOf(400.0, 0.2 * len * 111_320.0) / 111_320.0+ val perpLat = -dLon / len * offsetDeg+ val perpLon = dLat / len * offsetDeg / kotlin.math.cos(Math.toRadians(midLat)).coerceAtLeast(0.2)+ return GeoPoint(midLon + perpLon, midLat + perpLat)+}
maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.ktindex 706c0bceef..8f72e27410 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt@@ -129,13 +129,26 @@ internal object OfflineRouterTransit { context: Context, start: GeoPoint, end: GeoPoint+ ): RouteService.Route? = getTransitRouteOffline(context, start, end, departureOffsetSecs = 0)++ /**+ * The journey the planner finds [departureOffsetSecs] later: the raw+ * material for a transit alternative. Same-line next-bus results are+ * filtered out downstream by [AlternativeRoutes]; a different line or+ * service sequence survives.+ */+ suspend fun getTransitRouteOffline(+ context: Context,+ start: GeoPoint,+ end: GeoPoint,+ departureOffsetSecs: Int, ): RouteService.Route? = withContext(Dispatchers.Default) { val base = OfflineRouterLifecycle.transitBase(context) ?: return@withContext null val feeds = transitFeeds(base) if (feeds.isEmpty()) return@withContext null for (feed in feeds) {- planFeed(context, base, feed, start, end)?.let { return@withContext it }+ planFeed(context, base, feed, start, end, departureOffsetSecs)?.let { return@withContext it } } null }@@ -146,6 +159,7 @@ internal object OfflineRouterTransit { feed: String, start: GeoPoint, end: GeoPoint,+ departureOffsetSecs: Int = 0, ): RouteService.Route? { // The index is world-merged, so query times must be in the feed's // timezone. Journeys spanning two zones use the origin's — a known@@ -155,13 +169,14 @@ internal object OfflineRouterTransit { OfflineRouter.getFeedTimezoneNative(base, feed, start.latitude, start.longitude) }.getOrNull() )- val scheduled = planJourney(base, feed, start, end, clock, Overlay.EMPTY)+ val shifted = if (departureOffsetSecs == 0) clock else clock.copy(depSecs = clock.depSecs + departureOffsetSecs)+ val scheduled = planJourney(base, feed, start, end, shifted, Overlay.EMPTY) ?.takeIf { it.isNotEmpty() } ?: return null val overlay = realtimeOverlay(context, journeyStops(scheduled), clock) val raw = if (overlay.isEmpty) { scheduled } else {- planJourney(base, feed, start, end, clock, overlay) ?: scheduled+ planJourney(base, feed, start, end, shifted, overlay) ?: scheduled } return OfflineRouterRouteBuilder.buildRoute(context, raw, RouteService.TravelMode.TRANSIT) }
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 f2788d8dae..7e2b3824e0 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt@@ -264,6 +264,34 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli // re-plan every mode on each tab switch. // // The scan seed: one null per travel mode, merged over as each plan lands.+ /**+ * Genuinely different alternatives for the visible plan's mode+ * (primary excluded), gated by [AlternativeRoutes]. Only the+ * selected mode is planned, so this costs one extra plan.+ */+ @OptIn(ExperimentalCoroutinesApi::class)+ val alternatives: kotlinx.coroutines.flow.StateFlow<List<RouteService.Route>> = sheetRoute+ .flatMapLatest { route ->+ val plan = route as? SheetRoute.RoutePlan+ ?: return@flatMapLatest flowOf(emptyList())+ flow {+ emit(emptyList())+ emit(+ planWithAlternatives(+ getApplication(),+ SpecificFeature.Route(plan.waypoints),+ userPosition.value,+ plan.mode,+ ).drop(1),+ )+ }.flowOn(Dispatchers.Default)+ }+ .stateIn(+ scope = viewModelScope,+ started = SharingStarted.WhileSubscribed(5000),+ initialValue = emptyList(),+ )+ private fun emptyRoutes(): Map<RouteService.TravelMode, RouteService.RouteType?> = RouteService.TravelMode.entries.associateWith { null as RouteService.RouteType? } @OptIn(ExperimentalCoroutinesApi::class)
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 fc1f905a37..0e0e1ca095 100644--- a/maps/src/main/res/values/strings.xml+++ b/maps/src/main/res/values/strings.xml@@ -23,6 +23,8 @@ <string name="no_route_found">No route found</string> <!-- BottomSheet: Loading state while route is calculated --> <string name="generating_route">Generating Route…</string>+ <string name="alternative_routes_title">Other routes</string>+ <string name="alternative_selected">shown</string> <!-- MapPage: shown while the basemap style is read and patched, before the map can draw --> <string name="map_loading">Loading map…</string>
maps/src/test/java/com/vayunmathur/maps/util/AlternativeRoutesTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/AlternativeRoutesTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/AlternativeRoutesTest.ktnew file mode 100644index 0000000000..3b0ecbcc74--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/AlternativeRoutesTest.kt@@ -0,0 +1,135 @@+package com.vayunmathur.maps.util++import com.vayunmathur.library.map.GeoPoint+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlin.time.Duration.Companion.minutes++/** Diversity gating on synthetic routes: no graph or schedule needed. */+class AlternativeRoutesTest {++ private fun pt(lon: Double, lat: Double) = GeoPoint(lon, lat)++ private fun roadRoute(points: List<GeoPoint>, minutes: Int = 10): RouteService.Route {+ val steps = points.zipWithNext().map {+ RouteService.Step(+ distanceMeters = 100.0,+ staticDuration = 1.minutes,+ polyline = it.toList(),+ navInstruction = RouteService.API.NavInstruction(),+ travelMode = RouteService.TravelMode.DRIVE,+ )+ }+ return RouteService.Route(+ duration = minutes.minutes,+ distanceMeters = steps.sumOf { it.distanceMeters },+ polyline = points,+ step = steps,+ )+ }++ /** A straight east-west corridor and a genuinely different northern one. */+ private val primary = roadRoute(listOf(pt(0.0, 0.0), pt(0.01, 0.0), pt(0.02, 0.0), pt(0.03, 0.0)))+ private val northern = roadRoute(+ listOf(pt(0.0, 0.0), pt(0.01, 0.01), pt(0.02, 0.01), pt(0.03, 0.0)),+ )++ @Test+ fun `one-street swap driving variant is rejected`() {+ // Same corridor, jogged by ~11 m for one block: almost all shared.+ val swap = roadRoute(listOf(pt(0.0, 0.0), pt(0.01, 0.0001), pt(0.02, 0.0), pt(0.03, 0.0)))+ assertTrue(AlternativeRoutes.sharedGeometryRatio(primary, swap) >= AlternativeRoutes.MAX_SHARED_GEOMETRY_RATIO)+ assertEquals(emptyList(), AlternativeRoutes.diverseAlternatives(primary, listOf(swap), transit = false))+ }++ @Test+ fun `distinct corridor driving alternative is accepted`() {+ assertTrue(AlternativeRoutes.sharedGeometryRatio(primary, northern) < AlternativeRoutes.MAX_SHARED_GEOMETRY_RATIO)+ assertEquals(listOf(northern), AlternativeRoutes.diverseAlternatives(primary, listOf(northern), transit = false))+ }++ @Test+ fun `single-route case yields exactly one route`() {+ assertEquals(emptyList(), AlternativeRoutes.diverseAlternatives(primary, emptyList(), transit = false))+ assertEquals(emptyList(), AlternativeRoutes.diverseAlternatives(primary, listOf(primary), transit = false))+ }++ private fun transitRoute(+ legs: List<Triple<String, String, String>>,+ walkMeters: Double = 200.0,+ rideMeters: Double = 5_000.0,+ ): RouteService.Route {+ val steps = mutableListOf<RouteService.Step>()+ if (walkMeters > 0) {+ steps += RouteService.Step(+ distanceMeters = walkMeters, staticDuration = 3.minutes,+ polyline = listOf(pt(0.0, 0.0), pt(0.001, 0.0)),+ navInstruction = RouteService.API.NavInstruction(),+ travelMode = RouteService.TravelMode.WALK,+ )+ }+ legs.forEach { (line, board, alight) ->+ steps += RouteService.Step(+ distanceMeters = rideMeters, staticDuration = 10.minutes,+ polyline = listOf(pt(0.001, 0.0), pt(0.02, 0.0)),+ navInstruction = RouteService.API.NavInstruction(),+ travelMode = RouteService.TravelMode.TRANSIT,+ transitDetails = RouteService.API.TransitDetails(+ headsign = "Downtown", stopCount = 5,+ transitLine = RouteService.API.TransitLine(name = line, nameShort = line, color = "#000"),+ stopDetails = RouteService.API.StopDetails(+ arrivalTime = "10:10", departureTime = "10:00",+ arrivalStop = RouteService.API.Stop(alight),+ departureStop = RouteService.API.Stop(board),+ ),+ ),+ )+ }+ return RouteService.Route(+ duration = 20.minutes,+ distanceMeters = walkMeters + rideMeters * legs.size,+ polyline = listOf(pt(0.0, 0.0), pt(0.02, 0.0)),+ step = steps,+ )+ }++ @Test+ fun `early-alight walk variant of the same ride is rejected`() {+ val full = transitRoute(listOf(Triple("Red", "A", "C")))+ // Same line, same board, alighting one stop early and walking the+ // rest: a truncation of the primary's signature, not an alternative.+ val earlyAlight = transitRoute(listOf(Triple("Red", "A", "B")), walkMeters = 900.0, rideMeters = 3_000.0)+ assertEquals(emptyList(), AlternativeRoutes.diverseAlternatives(full, listOf(earlyAlight), transit = true))+ }++ @Test+ fun `same line re-departed later is not an alternative`() {+ val full = transitRoute(listOf(Triple("Red", "A", "C")))+ val nextBus = transitRoute(listOf(Triple("Red", "A", "C")))+ assertEquals(emptyList(), AlternativeRoutes.diverseAlternatives(full, listOf(nextBus), transit = true))+ }++ @Test+ fun `distinct-line transit alternative is accepted`() {+ val full = transitRoute(listOf(Triple("Red", "A", "C")))+ val otherLine = transitRoute(listOf(Triple("Blue", "A", "C")))+ assertEquals(listOf(otherLine), AlternativeRoutes.diverseAlternatives(full, listOf(otherLine), transit = true))+ }++ @Test+ fun `walk-heavy transit re-pad is rejected`() {+ val full = transitRoute(listOf(Triple("Red", "A", "C")))+ val walkHeavy = transitRoute(listOf(Triple("Blue", "B", "C")), walkMeters = 6_000.0, rideMeters = 2_000.0)+ assertTrue(AlternativeRoutes.walkShare(walkHeavy) > AlternativeRoutes.MAX_WALK_SHARE)+ assertEquals(emptyList(), AlternativeRoutes.diverseAlternatives(full, listOf(walkHeavy), transit = true))+ }++ @Test+ fun `eta order of accepted alternatives is preserved`() {+ val slower = roadRoute(listOf(pt(0.0, 0.0), pt(0.01, 0.012), pt(0.02, 0.012), pt(0.03, 0.0)), minutes = 18)+ val accepted = AlternativeRoutes.diverseAlternatives(primary, listOf(northern, slower), transit = false)+ assertEquals(listOf(northern, slower).filter { it in accepted }, accepted.filter { it in listOf(northern, slower) })+ assertEquals(northern, accepted.first())+ }+}