メインコンテンツまでスキップ

Faster-route detection

A newer version of the Navigation SDK is available
This page uses v1.6.2 of the Mapbox Navigation SDK. A newer version of the SDK is available. Learn about the latest version, v2.20.2, in the Navigation SDK documentation.

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.

Note
Faster route detection is disabled by default. If enabled, the Navigation SDK will only look for faster routes when the device is traveling along a route in turn-by-turn navigation mode.

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, replace FasterRouteObserver.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 by onFasterRoute(). It is true when alternatives[0].duration() is at least 10% faster than currentRoute.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()
}