Use this API to find the route and directions between two or more locations across a transportation network. The route result can include estimated travel time and distance, as well as driving directions for traversing the route. You can further enhance the routing experience using the current device location to track progress and provide navigation instructions (maneuvers) as the user travels the route. You can integrate driving directions with your device's text-to-speech capability and automatically recalculate a new route when the user leaves the current one.
The RouteTracker
object provides the following functionality using the current device location and an appropriate route result:
- Progress information relative to the next stop, to the next maneuver, or along the entire route
- Guidance for navigation as it's needed (when approaching a maneuver, for example)
- Automatic recalculation of a route if the device location goes off the route
The route result used for navigation must include stops and directions. To enable route recalculation while navigating, you must also provide the route task and routing parameters used to generate the route.
Track progress along a route
After a route has been calculated that includes at least two stops (a start location and one or more destinations) and driving directions, you can use the route tracker to track progress as the user traverses the route. To track the current device location, you must listen for location change events on the map view location display. As the device moves, pass the new location to the route tracker to update things such as the estimated remaining travel time and distance.
-
Create a route and directions between specified locations. Generally, the route starts at the user's current location. When defining the route parameters be sure to include stops and driving directions in the results.
NavigateActivity.ktUse dark colors for code blocks Copy // Get the default route parameters. // Then configure the route parameters to return stops and directions in the results. routeParameters = routeTask.createDefaultParameters().getOrElse { error-> return@launch showError("Error creating default parameters:${error.message}") }.apply { setStops(routeStops) returnDirections = true returnStops = true returnRoutes = true } // Create the route using these parameters...
-
To show progress along a route, display two polylines: one to represent the portion of the route that has been traveled (from the start to the current location) and another to show the portion that remains (from the current location to the destination). Add these geometries to the map view as graphics (using distinct symbols) and update them from the
RouteTracker
as the route changes.NavigateActivity.ktUse dark colors for code blocks Copy // Create a graphic (with a dashed line symbol) to represent the route. routeAheadGraphic = Graphic( geometry = routeGeometry, symbol = SimpleLineSymbol( style = SimpleLineSymbolStyle.Dash, color = Color(getColor(R.color.colorPrimary)), width = 5f ) ) // Create a graphic (solid) to represent the route that's been traveled (initially empty). routeTraveledGraphic = Graphic( geometry = routeGeometry, symbol = SimpleLineSymbol( style = SimpleLineSymbolStyle.Solid, color = Color.red, width = 5f ) ) // Add the graphics to the first graphics overlay in the mutable graphics overlays property used by the MapView composable. graphicsOverlays.first().graphics.addAll( listOf( routeAheadGraphic, routeTraveledGraphic ) )
-
Create a
RouteTracker
and pass in a route to travel. In the collect lambda for new voice guidance events, you can use the text property to have Android speak and/or display the text of the next direction.NavigateActivity.ktUse dark colors for code blocks Copy // Set up a RouteTracker for navigation along the calculated route. val routeTracker = RouteTracker( routeResult = routeResult, routeIndex = 0, skipCoincidentStops = true ) val trackingStatusJob = lifecycleScope.launch { routeTracker.trackingStatus.collect { trackingStatus -> // Collect tracking status changes to show the user current progress of the route... } }
NavigateActivity.ktUse dark colors for code blocks Copy routeTracker.setSpeechEngineReadyCallback { isTextToSpeechInitialized.get() && textToSpeech?.isSpeaking == false } // Play the direction voice guidance. lifecycleScope.launch { // Listen for new voice guidance events. routeTracker.newVoiceGuidance.collect { voiceGuidance -> // Handle each voice guidance event as it arrives... } }
-
To enable rerouting, first create
ReroutingParameters
. Then, if the route task supports rerouting, pass the rerouting parameters to the enable rerouting function.NavigateReroutingActivity.ktUse dark colors for code blocks Copy // Check if this route task support rerouting. if (routeTask.getRouteTaskInfo().supportsRerouting) { // Set up the re-routing parameters. val reroutingParameters = ReroutingParameters( routeTask = routeTask, routeParameters = routeParameters ).apply { strategy = ReroutingStrategy.ToNextWaypoint visitFirstStopOnStart = false } // Enable automatic rerouting. routeTracker.enableRerouting(reroutingParameters).getOrElse { showError("Error enabling rerouting.") } } // Collect each reroute completed event as it arrives. routeTracker.rerouteCompleted.collect { trackingStatusResult -> val trackingStatus = trackingStatusResult.getOrElse { return@collect } // Use the trackingStatus to display UI updates... }
-
Enable location display on the map view and, optionally, create a simulated data source. Then collect the device location updates and pass each new location to the
Last, don't forget to start the modified data source.track
function ofLocation() RouteTracker
. The tracker will update the status when it gets a new location, including whether the user is off the route.NavigateReroutingActivity.ktUse dark colors for code blocks Copy // Create a route tracker location data source to snap the location display to the route. routeTrackerLocationDataSource = RouteTrackerLocationDataSource( routeTracker = routeTracker ) // Configure the mutable location display property used by the MapView composable. locationDisplay.apply { -> // Assign the route tracker location data source as the data source for the location display. dataSource = routeTrackerLocationDataSource setAutoPanMode(LocationDisplayAutoPanMode.Navigation) } // Start the location display's data source. lifecycleScope.launch { locationDisplay.dataSource.start().getOrElse { error -> showError("Error starting LocationDataSource: ${error.message}") } }
To use a simulated location data source with route tracking, wrap it in the route tracker location data source.
NavigateActivity.ktUse dark colors for code blocks Copy val routeTrackerLocationDataSource = RouteTrackerLocationDataSource( routeTracker = routeTracker, locationDataSource = simulatedLocationDataSource )
-
Collect the route tracker's tracking status and use it to create a status update for the user. This might be UI updates that include the travel time or distance remaining for the route or until the next maneuver (for example, a turn). You can also warn the user if they are off the route (especially if rerouting is not enabled). See the Report progress for more information about the types of progress provided by the route tracker and for a code example.
The following code checks whether the user is off route and either provides a warning or updates the remaining distance and time to the destination. It also updates the graphics that show the portion of the route that's been traveled and the portion that remains.
NavigateReroutingActivity.ktUse dark colors for code blocks Copy routeTracker.trackingStatus.collect { trackingStatus -> // Check if navigation is on route. if (trackingStatus.isOnRoute && !trackingStatus.isCalculatingRoute) { // If still on route, check the destination status. when (trackingStatus.destinationStatus) { DestinationStatus.NotReached -> { // Set geometries for the route behind and the remaining route. routeAheadGraphic.geometry = trackingStatus.routeProgress.remainingGeometry routeTraveledGraphic.geometry = trackingStatus.routeProgress.traversedGeometry // Get the distance remaining in kilometers. val distanceRemainingText = trackingStatus.routeProgress.remainingDistance.displayText val distanceRemainingUnits = trackingStatus.routeProgress.remainingDistance.displayTextUnits.abbreviation val distanceRemainingMessage = distanceRemainingText + distanceRemainingUnits statusMessage.appendLine("Distance remaining: $distanceRemainingMessage") // Get the time remaining in minutes val timeRemaining = DateUtils.formatElapsedTime((trackingStatus.destinationProgress.remainingTime * 60).toLong()) statusMessage.appendLine("Time remaining: $timeRemaining") } } } else { statusMessage.appendLine("Off route, rerouting...") }
-
Use the new voice guidance event handler to give driving instructions to the user. The voice guidance object that's passed into the event contains text that you can pass to a text-to-speech engine or use to update instructions shown in the UI.
NavigateReroutingActivity.ktUse dark colors for code blocks Copy // Listen for new voice guidance events. routeTracker.newVoiceGuidance.collect { voiceGuidance -> // Use Android's text to speech to speak the voice guidance. // Note that TextToSpeech is is an Android class written in Java, so named arguments could not be used. textToSpeech?.speak( /* text = */ voiceGuidance.text, /* queueMode = */ TextToSpeech.QUEUE_FLUSH, /* params = */ null, /* utteranceId = */ null ) // Display the next direction on screen from the same text used by voice guidance. nextDirectionText.text = getString(R.string.next_direction, voiceGuidance.text) }
-
If route recalculation is enabled, you can handle the route tracker's reroute completed event to update the route (a graphic, for example) displayed in the map view. See Handle rerouting for more information.
NavigateReroutingActivity.ktUse dark colors for code blocks Copy routeTracker.rerouteCompleted.collect { trackingStatusResult -> // The rerouteCompleted state flow emits tracking status results, which you can use to display UI updates. // For example, create an Circle symbol every time the device went off route and the // route had to be re-calculated. val trackingStatus = trackingStatusResult.getOrElse { return@collect } val currentLocationPoint = trackingStatus.displayLocation.position graphicsOverlay.graphics.add( Graphic( geometry = currentLocationPoint, symbol = SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.red, 15F) ) ) }
Report progress
The route tracker's TrackingStatus
object provides values that you can use to report progress as the user traverses a route. This object is available from the RouteTracker
directly or when the tracking status changes, allowing you to evaluate route progress any time it changes. The basic status it provides is whether the user is still traveling the route. If rerouting is enabled for the tracker, a new route will be created whenever this value is false (if the current location is on the network).
The tracking status object also provides progress relative to the following parts of the route.
- Destination — Describes progress to the next stop in the route
- Maneuver — Describes progress to the next maneuver (driving instruction, for example)
- Route — Describes progress along the entire route
Each of these types of progress is represented by the TrackingProgress
object with the following information:
- Remaining distance — The distance remaining to the relevant location (next stop, next maneuver, or route end)
- Remaining geometry — A polyline representing the portion of the route between the current location and the relevant location (next stop, next maneuver, or route end)
- Remaining time — The time remaining to the relevant location (next stop, next maneuver, or route end)
- Traversed geometry — A polyline representing the portion of the route between the start of the route and the current location
The tracking status also allows you access to the route that's being traversed. Using the current maneuver index, you can find the current maneuver from the route's list of directions.
val currentRoute = trackingStatus.routeResult.routes.first()
val currentManeuver = currentRoute.directionManeuvers[trackingStatus.currentManeuverIndex]
Voice guidance
To give instructions to the user as they are approaching a maneuver, you can handle the new voice guidance event. Voice guidance notifications are generated at the time they are needed while traveling the route. You can use the text provided by the voice guidance to play the instruction (using an available text-to-speech engine), or to update driving instructions text in the UI.
The current speed, distance to the next maneuver, and the time required to enunciate an instruction are all considered when generating text for voice guidance. The driving directions text from the route and the distance to the maneuver can be used in the guidance, such as "in 300 meters, turn right on VENICE BLVD". Voice guidance text can be categorized as one of the following types of notifications:
- Long — Occurring immediately after a maneuver starts to describe the next one, it is formatted using the full directions text. "Go straight along Main Street, and in one mile turn right on First Street", for example.
- Moderate — Occurring 20 to 30 seconds before the maneuver, it is formatted using a parsed down form of the direction text. "In half a mile, turn right on First Street", for example.
- Short — Occurring approximately 10 seconds before the maneuver, it is formatted using a terse form of the direction text. "Turn right on First Street", for example.
- Combined — Two consecutive short maneuvers can be combined into a single voice guidance. "Turn right on First Street, then left", for example.
For any particular maneuver, one or more of these types of notifications can be generated. Abbreviations in directions text can be expanded when the voice guidance is created. "W Carolina destination is ahead" can be generated as "West Carolina destination is ahead", for example. Characters that are used it text directions, such as slashes, dashes, and so on, can be dropped from the voice guidance text.
Handle Rerouting
You can enable rerouting for a route tracker only if the underlying route data (online service or local dataset) supports rerouting. Currently, rerouting is only supported for routes created from a local network dataset. You can check the route task information to verify that rerouting is supported. If it is, you can enable rerouting on the route tracker. To enable rerouting, you need the following:
-
The original route task that was used to calculate the route used by the tracker
-
The original route task parameters used to calculate the tracker route
-
One of the following rerouting strategy values to use for the creation of new routes
- Re-sequence stops only — Optimize the new route for the remaining stops.
- To next stop — Reroute to the next unvisited stop in the original order.
- To next waypoint — Reroute to the next unvisited waypoint, rest break, or stop.
-
Knowledge of whether the first stop in the route must be visited when creating the new route
You can cancel rerouting while a new route is being calculated and disable rerouting to turn that functionality off. Route tracker events allow you to respond when calculation of a new route begins and when it completes. You can use the completion event to display the new route in the map view.