Navigate route with rerouting

View on GitHubSample viewer app

Navigate between two points and dynamically recalculate an alternate route when the original route is unavailable.

Image of navigate route with rerouting

Use case

While traveling between destinations, field workers use navigation to get live directions based on their locations. In cases where a field worker makes a wrong turn, or if the route suggested is blocked due to a road closure, it is necessary to calculate an alternate route to the original destination.

How to use the sample

Tap "Navigate" to simulate traveling and to receive directions from a preset starting point to a preset destination. Observe how the route is recalculated when the simulation does not follow the suggested route. Tap "Recenter" to reposition the viewpoint. Tap "Reset" to start the simulation from the beginning.

How it works

  1. Create a RouteTask using local network data.
  2. Generate default RouteParameters using RouteTask.createDefaultParameters().
  3. Set returnRoutes, returnStops, and returnDirections on the RouteParameters to true.
  4. Add Stops to the parameters' list of stops using RouteParameters.setStops(...).
  5. Solve the route using routeTask.solveRoute(routeParameters) to get an RouteResult.
  6. Create an RouteTracker using the route result, and the index of the desired route to take.
  7. Enable rerouting in the route tracker using routeTracker.enableRerouting(reroutingParameters). Pass ReroutingStrategy.ToNextWaypoint as the value of strategy to specify that in the case of a reroute, the new route goes from present location to next waypoint or stop.
  8. Retrieve the routeTracker.trackingStatus state flow values to track status and progress updates as a route is traversed.

Relevant API

  • DestinationStatus
  • DirectionManeuver
  • Location
  • LocationDataSource
  • ReroutingStrategy
  • Route
  • RouteParameters
  • RouteTask
  • RouteTracker
  • RouteTrackerLocationDataSource
  • SimulatedLocationDataSource
  • Stop
  • VoiceGuidance

About the data

The San Diego Geodatabase route taken in this sample goes from the San Diego Convention Center, site of the annual Esri User Conference, to the Fleet Science Center, San Diego.

Additional information

The route tracker will start a rerouting calculation automatically as necessary when the device's location indicates that it is off-route. The route tracker also validates that the device is "on" the transportation network. If it is not (e.g. in a parking lot), rerouting will not occur until the device location indicates that it is back "on" the transportation network.

Tags

directions, maneuver, navigation, route, turn-by-turn, voice

Sample Code

NavigateRouteWithReroutingViewModel.ktNavigateRouteWithReroutingViewModel.ktMainActivity.ktDownloadActivity.ktNavigateRouteWithReroutingScreen.kt
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/* Copyright 2025 Esri
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.esri.arcgismaps.sample.navigateroutewithrerouting.components

import android.app.Application
import android.speech.tts.TextToSpeech
import android.text.format.DateUtils
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.content.ContextCompat
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.arcgismaps.Color
import com.arcgismaps.geometry.Geometry
import com.arcgismaps.geometry.Point
import com.arcgismaps.geometry.Polyline
import com.arcgismaps.geometry.SpatialReference
import com.arcgismaps.location.LocationDisplayAutoPanMode
import com.arcgismaps.location.RouteTrackerLocationDataSource
import com.arcgismaps.location.SimulatedLocationDataSource
import com.arcgismaps.location.SimulationParameters
import com.arcgismaps.mapping.ArcGISMap
import com.arcgismaps.mapping.BasemapStyle
import com.arcgismaps.mapping.symbology.SimpleLineSymbol
import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
import com.arcgismaps.mapping.symbology.SimpleMarkerSymbol
import com.arcgismaps.mapping.symbology.SimpleMarkerSymbolStyle
import com.arcgismaps.mapping.view.Graphic
import com.arcgismaps.mapping.view.GraphicsOverlay
import com.arcgismaps.mapping.view.LocationDisplay
import com.arcgismaps.navigation.DestinationStatus
import com.arcgismaps.navigation.ReroutingParameters
import com.arcgismaps.navigation.ReroutingStrategy
import com.arcgismaps.navigation.RouteTracker
import com.arcgismaps.navigation.TrackingStatus
import com.arcgismaps.tasks.networkanalysis.RouteParameters
import com.arcgismaps.tasks.networkanalysis.RouteResult
import com.arcgismaps.tasks.networkanalysis.RouteTask
import com.arcgismaps.tasks.networkanalysis.Stop
import com.arcgismaps.toolkit.geoviewcompose.MapViewProxy
import com.esri.arcgismaps.sample.navigateroutewithrerouting.R
import com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
import java.io.File
import java.time.Instant

class NavigateRouteWithReroutingViewModel(application: Application) :
    AndroidViewModel(application) {

    // Path of the San Diego transport network used by the route task
    private val provisionPath: String by lazy {
        application.getExternalFilesDir(null)?.path.toString() +
                File.separator + application.getString(R.string.navigate_route_with_rerouting_app_name)
    }

    // Passed to the composable MapView to set the mapViewProxy
    val mapViewProxy = MapViewProxy()

    // The map to display basemap, route traveled & route ahead graphics
    val arcGISMap = ArcGISMap(BasemapStyle.ArcGISStreets)

    // Graphics overlay to display the route ahead and traveled graphics
    val graphicsOverlay = GraphicsOverlay()

    // Keep track of the the location display job when navigation is enabled
    private var locationDisplayJob: Job? = null

    // Default location display object, which is updated by rememberLocationDisplay
    private var locationDisplay: LocationDisplay = LocationDisplay()

    // Starting point: San Diego Convention Center
    private val startingStop = Stop(Point(-117.160386, 32.706608, SpatialReference.wgs84()))
        .apply { name = "San Diego Convention Center" }

    // Destination point: Fleet Science Center
    private val destinationStop = Stop(Point(-117.146679, 32.730351, SpatialReference.wgs84()))
        .apply { name = "RH Fleet Aerospace Museum" }

    // Generate a route with directions and stops for navigation
    private val routeTask = RouteTask(
        pathToDatabase = "$provisionPath/sandiego.geodatabase",
        networkName = "Streets_ND"
    )

    // The route parameters needed to calculate a route from a start and stop point
    private var routeParameters = RouteParameters()

    // The resulted route from the route task using the route parameters
    private var routeResult: RouteResult? = null

    // Instance of the route ahead polyline
    private var routeAheadGraphic: Graphic = Graphic(
        symbol = SimpleLineSymbol(
            SimpleLineSymbolStyle.Dash,
            Color(getColorArgb(com.esri.arcgismaps.sample.sampleslib.R.color.colorPrimary)),
            3f
        )
    )

    // Graphic to represent the route that's been traveled (initially empty)
    private var routeTraveledGraphic: Graphic = Graphic(
        symbol = SimpleLineSymbol(
            SimpleLineSymbolStyle.Solid,
            Color.black,
            3f
        )
    )

    var distanceRemainingText by mutableStateOf("")
        private set

    var timeRemainingText by mutableStateOf("")
        private set

    var nextDirectionText by mutableStateOf("")
        private set

    var isNavigateButtonEnabled by mutableStateOf(true)
        private set

    var isRecenterButtonEnabled by mutableStateOf(false)
        private set

    // Boolean to check if Android text-speech is initialized
    private var isTextToSpeechInitialized = false

    // Instance of Android text-speech
    private var textToSpeech: TextToSpeech? = null

    // JSON of polylines of the path for the simulated data source
    private val polylineJSON: String by lazy {
        application.getString(R.string.simulation_path_json)
    }

    // Polyline representing simulation path
    private val simulationPolyline = Geometry.fromJsonOrNull(polylineJSON) as Polyline

    // Create a ViewModel to handle dialog interactions
    val messageDialogVM: MessageDialogViewModel = MessageDialogViewModel()

    fun initialize(locationDisplay: LocationDisplay) {
        // Set the location display to be used by this view model
        this.locationDisplay = locationDisplay
        // Initialize text-to-speech to replay navigation voice guidance
        val context = getApplication<Application>().applicationContext
        textToSpeech = TextToSpeech(context) { status ->
            if (status == TextToSpeech.SUCCESS) {
                textToSpeech?.language = context.resources.configuration.locales[0]
                isTextToSpeechInitialized = true
            }
        }
        // Load and set the route parameters
        viewModelScope.launch {
            routeParameters = routeTask.createDefaultParameters()
                .getOrElse { return@launch messageDialogVM.showMessageDialog(it) }.apply {
                    setStops(listOf(startingStop, destinationStop))
                    returnDirections = true
                    returnStops = true
                    returnRoutes = true
                }
            // Load the map
            arcGISMap.load().onFailure { return@launch messageDialogVM.showMessageDialog(it) }
            // Get the solved route result
            routeResult = routeTask.solveRoute(routeParameters).getOrElse {
                return@launch messageDialogVM.showMessageDialog(it)
            }
            // Reset navigation to initial state
            resetNavigation()
        }
    }

    /**
     * Start the navigation along the provided route using the [routeResult] and
     * collects updates in the location using the MapView's location display.
     * */
    fun startNavigation() {
        // Set up a simulated location data source which simulates movement along the route
        val simulationParameters = SimulationParameters(
            startTime = Instant.now(),
            velocity = 35.0,
            horizontalAccuracy = 5.0,
            verticalAccuracy = 5.0
        )
        // Create the simulated data source using the polyline geometry and parameters
        val simulatedLocationDataSource = SimulatedLocationDataSource(
            polyline = simulationPolyline,
            parameters = simulationParameters
        )
        // Set up a RouteTracker for navigation along the calculated route
        val routeTracker = routeResult?.let {
            RouteTracker(
                routeResult = it,
                routeIndex = 0,
                skipCoincidentStops = true
            ).apply {
                setSpeechEngineReadyCallback {
                    isTextToSpeechInitialized && textToSpeech?.isSpeaking == false
                }
            }
        } ?: return messageDialogVM.showMessageDialog("Error retrieving route result")
        // Manage the job which triggers the location display
        locationDisplayJob = with(viewModelScope) {
            launch {
                // Check if this route task supports 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 re-routing
                    routeTracker.enableRerouting(parameters = reroutingParameters)
                        .onFailure { return@launch messageDialogVM.showMessageDialog(it) }
                }
                // Create a route tracker location data source to snap the location display to the route
                val routeTrackerLocationDataSource = RouteTrackerLocationDataSource(
                    routeTracker = routeTracker,
                    locationDataSource = simulatedLocationDataSource
                )
                locationDisplay.apply {
                    // Set the simulated location data source as the location data source for this app
                    dataSource = routeTrackerLocationDataSource.also {
                        // Start the location data source
                        it.start().onFailure { return@launch messageDialogVM.showMessageDialog(it) }
                    }
                    // Set the auto pan to navigation mode
                    setAutoPanMode(LocationDisplayAutoPanMode.Navigation)
                }
                // Plays the direction voice guidance
                updateVoiceGuidance(routeTracker)
                // Zoom in the scale to focus on the navigation route
                mapViewProxy.setViewpointScale(10000.0)
            }
            launch {
                // Listen for changes in location
                locationDisplay.location.collect {
                    // Get the route's tracking status
                    val trackingStatus = routeTracker.trackingStatus.value ?: return@collect
                    // Displays the remaining and traversed route
                    updateRouteGraphics(trackingStatus)
                    // Display route status and directions info
                    displayRouteInfo(trackingStatus)
                    // Disable navigation button
                    isNavigateButtonEnabled = false
                }
            }
            launch {
                // Automatically enable recenter button when navigation pan is disabled
                locationDisplay.autoPanMode.filter { it == LocationDisplayAutoPanMode.Off }
                    .collect { isRecenterButtonEnabled = true }
            }
            launch {
                routeTracker.rerouteStarted.collect {
                    nextDirectionText = "Re-routing..."
                }
            }
        }
    }

    /**
     * Displays the route distance and time information using [trackingStatus].
     * When destination is reached the location data source is stopped.
     */
    private suspend fun displayRouteInfo(trackingStatus: TrackingStatus) {
        // Get remaining distance information
        val remainingDistance = trackingStatus.destinationProgress.remainingDistance
        val remainingDistanceValue = remainingDistance.displayText
        val remainingDistanceUnits = remainingDistance.displayTextUnits.abbreviation
        // Convert remaining minutes to hours:minutes:seconds
        val remainingTimeString = DateUtils.formatElapsedTime(
            (trackingStatus.destinationProgress.remainingTime * 60).toLong()
        )
        // Update text views
        timeRemainingText = remainingTimeString
        distanceRemainingText = "$remainingDistanceValue $remainingDistanceUnits"
        // If the destination has been reached
        if (trackingStatus.destinationStatus == DestinationStatus.Reached) {
            // Stop the location data source
            locationDisplay.dataSource.stop()
        }
    }

    /**
     * Update the remaining and traveled route graphics using [trackingStatus]
     */
    private fun updateRouteGraphics(trackingStatus: TrackingStatus) {
        trackingStatus.routeProgress.let {
            // Set geometries for the route ahead and the remaining route
            routeAheadGraphic.geometry = it.remainingGeometry
            routeTraveledGraphic.geometry = it.traversedGeometry
        }
    }

    /**
     * Initialize and add route travel graphics to the map using [routeResult]'s [Polyline] geometry.
     */
    private fun createRouteGraphics() {
        // Clear any graphics from the current graphics overlay
        graphicsOverlay.graphics.clear()
        // Set the view point to show the whole route
        val routeGeometry = routeResult?.routes?.get(0)?.routeGeometry
        // Set the geometry of the route ahead to the solved route geometry
        routeAheadGraphic.geometry = routeGeometry
        // Create the start and stop marker graphics
        val startGraphic = Graphic(
            geometry = startingStop.geometry,
            symbol = SimpleMarkerSymbol(
                style = SimpleMarkerSymbolStyle.Cross,
                color = Color.green,
                size = 20f
            )
        )
        val destinationGraphic = Graphic(
            geometry = destinationStop.geometry,
            symbol = SimpleMarkerSymbol(
                style = SimpleMarkerSymbolStyle.X,
                color = Color.red,
                size = 20f
            )
        )
        // Add the graphics to the graphics overlays
        graphicsOverlay.graphics.addAll(
            listOf(routeAheadGraphic, routeTraveledGraphic, startGraphic, destinationGraphic)
        )
    }

    /**
     * Resets the navigation back to the initial state by stopping the
     * [locationDisplay]'s datasource and cancels related coroutine tasks.
     */
    fun resetNavigation() {
        // Reset the navigation if button is clicked
        viewModelScope.launch {
            if (locationDisplayJob?.isActive == true) {
                // Stop location data sources
                locationDisplay.dataSource.stop()
                // Reset location display auto-pan-mode
                locationDisplay.setAutoPanMode(LocationDisplayAutoPanMode.Off)
                // Cancel the coroutine job
                locationDisplayJob?.cancelAndJoin()
            }
            // Set the map view view point to show the whole route
            routeResult?.routes?.get(0)?.routeGeometry?.extent?.let {
                mapViewProxy.setViewpointGeometry(it, 50.0)
            }
            mapViewProxy.setViewpointRotation(0.0)
            createRouteGraphics()
            isNavigateButtonEnabled = true
            textToSpeech?.stop()
        }
    }

    /**
     * Uses Android's [textToSpeech] to speak to say the latest
     * voice guidance from the [routeTracker] out loud.
     */
    private suspend fun updateVoiceGuidance(routeTracker: RouteTracker) {
        // Listen for new voice guidance events
        routeTracker.newVoiceGuidance.collect { voiceGuidance ->
            // Use Android's text to speech to speak the voice guidance
            textToSpeech?.speak(voiceGuidance.text, TextToSpeech.QUEUE_FLUSH, null, null)
            // Set next direction text
            nextDirectionText = voiceGuidance.text
        }
    }

    fun recenterNavigation() {
        locationDisplay.setAutoPanMode(LocationDisplayAutoPanMode.Navigation)
        isRecenterButtonEnabled = false
    }

    private fun getColorArgb(id: Int): Int {
        return ContextCompat.getColor(getApplication(), id)
    }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.