Faster-route detection
Traffic conditions along a route can change while you're navigating, causing the initial route to no longer be as fast as it was when you departed. The Navigation SDK can detect when a faster route becomes available. This page describes how the Navigation SDK provides you with faster route information and what you can do with that information.
The Navigation SDK's FasterRouteObserver
interface alerts you when the Navigation SDK detects a faster route and provides you with faster route information.
First, create the FasterRouteObserver
interface object:
val fasterRouteObserver = object : FasterRouteObserver {
override fun restartAfterMillis() = FasterRouteObserver.DEFAULT_INTERVAL_MILLIS
override fun onFasterRoute(currentRoute: DirectionsRoute, alternatives: List<DirectionsRoute>, isAlternativeFaster: Boolean) {
}
}
In the code snippet above:
restartAfterMillis()
is the number of milliseconds the Navigation SDK will wait until it once again looks for a faster route. If you want to set a custom interval, replaceFasterRouteObserver.DEFAULT_INTERVAL_MILLIS
with your preferred number of milliseconds. An interval less than 2 minutes (120000 milliseconds) will fail. Mapbox's recommended interval is every 5 minutes (300000 milliseconds).isAlternativeFaster
is a boolean returned byonFasterRoute()
. It istrue
whenalternatives[0].duration()
is at least 10% faster thancurrentRoute.durationRemaining()
.
Attach the FasterRouteObserver
object to your already-instantiated MapboxNavigation
object.
mapboxNavigation.attachFasterRouteObserver(fasterRouteObserver)
Giving MapboxNavigation
a list of routes with mapboxNavigation.setRoutes(newRoutes)
will tell MapboxNavigation
to use and draw the faster route(s) passed through this method. A logical place to put this setRoutes()
method is inside of the FasterRouteObserver
's onFasterRoute()
callback:
val fasterRouteObserver = object : FasterRouteObserver {
override fun restartAfterMillis() = FasterRouteObserver.DEFAULT_INTERVAL_MILLIS
override fun onFasterRoute(currentRoute: DirectionsRoute, alternatives: List<DirectionsRoute>, isAlternativeFaster: Boolean) {
mapboxNavigation.setRoutes(alternatives)
}
}
Don’t forget to detach the FasterRouteObserver
interface to stop requesting faster routes:
override fun onStop() {
super.onStop()
mapView.onStop()
mapboxNavigation.detachFasterRouteObserver()
}