Navigate route

View on GitHubSample viewer app

Use a routing service to navigate between two points.

Image of navigate route

Use case

Navigation is often used by field workers while traveling between two points to get live directions based on their location.

How to use the sample

Tap 'Navigate Route' to simulate travelling and to receive directions from a preset starting point to a preset destination. Tap 'Recenter' to focus on the simulated location, or press 'Navigate Route' again to restart navigation.

How it works

  1. Create a RouteTask using a URL to an online route service.
  2. Generate default RouteParameters using routeTask.createDefaultParameters().
  3. Set returnStops and returnDirections on the parameters to true.
  4. Add Stops to the parameters stops collection for each destination.
  5. Solve the route using routeTask.solveRoute(routeParameters) to get a RouteResult.
  6. Create a RouteTracker using the route result, and the index of the desired route to take.
  7. Create a RouteTrackerLocationDataSource with the route tracker and simulated location data source to snap the location display to the route.
  8. Collect location updates using MapView.LocationDisplay.Location
  9. Get the TrackingStatus using the RouteTracker.trackingStatus.value and use it to display updated route information. Tracking status includes a variety of information on the route progress, such as the remaining distance, remaining geometry or traversed geometry (represented by a Polyline), or the remaining time (Double), amongst others.
  10. Collect new voice guidance updates using RouteTracker.newVoiceGuidance to get the VoiceGuidance whenever new instructions are available. From the voice guidance, get the String representing the directions and use a text-to-speech engine to output the maneuver directions.
  11. To establish whether the destination has been reached, get the DestinationStatus from the tracking status. If the destination status is DestinationStatus.Reached, and the remainingDestinationCount is 1, we have arrived at the destination and can stop routing. If there are several destinations in your route, and the remaining destination count is greater than 1, switch the route tracker to the next destination.

Relevant API

  • DestinationStatus
  • Location
  • LocationDataSource
  • Route
  • RouteParameters
  • RouteTask
  • RouteTracker
  • Stop
  • VoiceGuidance

Offline data

None

About the data

The 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

This sample uses the GeoView-Compose Toolkit module to be able to implement a composable MapView.

Tags

directions, geoview-compose, maneuver, navigation, route, toolkit, turn-by-turn, voice

Sample Code

NavigateRouteViewModel.ktNavigateRouteViewModel.ktMainActivity.ktNavigateRouteScreen.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/* Copyright 2024 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.navigateroute.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.core.content.ContextCompat.getString
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.arcgismaps.Color
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.Viewpoint
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.RouteTracker
import com.arcgismaps.navigation.TrackingStatus
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.navigateroute.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.time.Instant
import java.util.concurrent.atomic.AtomicBoolean

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

    val map = ArcGISMap(BasemapStyle.ArcGISStreets)

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

    // generate a route with directions and stops for navigation
    private val routeTask = RouteTask(getString(application, R.string.routing_service_url))

    // destination list of stops for the RouteParameters
    private val routeStops = listOf(
        // San Diego Convention Center
        Stop(Point(-117.160386, 32.706608, SpatialReference.wgs84())),
        // USS San Diego Memorial
        Stop(Point(-117.173034, 32.712327, SpatialReference.wgs84())),
        // RH Fleet Aerospace Museum
        Stop(Point(-117.147230, 32.730467, SpatialReference.wgs84()))
    )

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

    // 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()

    private var routeResult: RouteResult? = null

    // instance of the route ahead polyline
    private var routeAheadGraphic: Graphic = Graphic()

    // instance of the route traveled polyline
    private var routeTraveledGraphic: Graphic = Graphic()

    var distanceRemainingText by mutableStateOf("")
        private set

    var timeRemainingText by mutableStateOf("")
        private set

    var nextDirectionText by mutableStateOf("")
        private set

    var nextStopText 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 = AtomicBoolean(false)

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

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

    init {
        // create text-to-speech to replay navigation voice guidance
        textToSpeech = TextToSpeech(application) { status ->
            if (status != TextToSpeech.ERROR) {
                textToSpeech?.language =
                    getApplication<Application>().resources.configuration.locales[0]
                isTextToSpeechInitialized.set(true)
            }
        }

        viewModelScope.launch {
            // load and set the route parameters
            val routeParameters = routeTask.createDefaultParameters().getOrElse {
                return@launch messageDialogVM.showMessageDialog(
                    title = "Error creating default parameters",
                    description = it.message.toString()
                )
            }.apply {
                setStops(routeStops)
                returnDirections = true
                returnStops = true
                returnRoutes = true
            }

            // get the solved route result
            routeResult = routeTask.solveRoute(routeParameters).getOrElse {
                return@launch messageDialogVM.showMessageDialog(
                    title = "Error solving route",
                    description = it.message.toString()
                )
            }

            // 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() {
        val routeResult = routeResult
            ?: return messageDialogVM.showMessageDialog("Error retrieving route result")
        // get the route's geometry from the route result
        val routeGeometry: Polyline = routeResult.routes[0].routeGeometry
            ?: return messageDialogVM.showMessageDialog("Route is missing geometry")

        // set up a simulated location data source which simulates movement along the route
        val simulationParameters = SimulationParameters(
            Instant.now(),
            velocity = 35.0,
            horizontalAccuracy = 5.0,
            verticalAccuracy = 5.0
        )

        // create the simulated data source using the geometry and parameters
        val simulatedLocationDataSource = SimulatedLocationDataSource(
            polyline = routeGeometry,
            parameters = simulationParameters
        )

        // set up a RouteTracker for navigation along the calculated route
        val routeTracker = RouteTracker(
            routeResult = routeResult,
            routeIndex = 0,
            skipCoincidentStops = true
        ).apply {
            setSpeechEngineReadyCallback {
                isTextToSpeechInitialized.get() && textToSpeech?.isSpeaking == false
            }
        }

        // create a route tracker location data source to snap the location display to the route
        val routeTrackerLocationDataSource = RouteTrackerLocationDataSource(
            routeTracker = routeTracker,
            locationDataSource = simulatedLocationDataSource
        )

        locationDisplayJob = with(viewModelScope) {
            launch {
                // automatically enable recenter button when navigation pan is disabled
                locationDisplay.autoPanMode.filter { it == LocationDisplayAutoPanMode.Off }
                    .collect { isRecenterButtonEnabled = true }
            }

            launch {
                // set the simulated location data source as the location data source for this app
                locationDisplay.dataSource = routeTrackerLocationDataSource

                // start the location data source
                locationDisplay.dataSource.start().getOrElse {
                    messageDialogVM.showMessageDialog(
                        title = "Error starting location data source",
                        description = it.message.toString()
                    )
                }

                // set the auto pan to navigation mode
                locationDisplay.setAutoPanMode(LocationDisplayAutoPanMode.Navigation)

                // data source has started, display stop message
                nextStopText = getStringArray(R.array.stop_message)[0]

                // plays the direction voice guidance
                updateVoiceGuidance(routeTracker)

                launch {
                    // 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(routeTracker, trackingStatus)
                    // disable navigation button
                    isNavigateButtonEnabled = false
                }
            }
        }
    }

    /**
     * Displays the route distance and time information using [trackingStatus], and
     * switches destinations using [routeTracker]. When final destination is reached,
     * the location data source is stopped.
     */
    private suspend fun displayRouteInfo(
        routeTracker: RouteTracker,
        trackingStatus: TrackingStatus
    ) {
        // get remaining distance information
        val remainingDistance = trackingStatus.destinationProgress.remainingDistance
        // convert remaining minutes to hours:minutes:seconds
        val remainingTimeString =
            DateUtils.formatElapsedTime((trackingStatus.destinationProgress.remainingTime * 60).toLong())

        // update text views
        timeRemainingText = getString(R.string.time_remaining) + " " + remainingTimeString
        distanceRemainingText = getString(R.string.distance_remaining) + " " +
                remainingDistance.displayText + " " +
                remainingDistance.displayTextUnits.abbreviation

        // if a destination has been reached
        if (trackingStatus.destinationStatus == DestinationStatus.Reached) {
            // if there are more destinations to visit. Greater than 1 because the start point is considered a "stop"
            if (trackingStatus.remainingDestinationCount > 1) {
                // switch to the next destination
                routeTracker.switchToNextDestination().getOrElse {
                    return messageDialogVM.showMessageDialog(
                        title = "Error retrieving next destination",
                        description = it.message.toString()
                    )
                }
                // set second stop message
                nextStopText = getStringArray(R.array.stop_message)[1]
            } else {
                // the final destination has been reached,
                // stop the location data source
                locationDisplay.dataSource.stop()
                // set last stop message
                nextStopText = getStringArray(R.array.stop_message)[2]
            }
        }
    }

    /**
     * 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 map view view point to show the whole route
        val routeGeometry = routeResult?.routes?.get(0)?.routeGeometry

        // create a graphic (with a dashed line symbol) to represent the route
        routeAheadGraphic = Graphic(
            routeGeometry,
            SimpleLineSymbol(
                SimpleLineSymbolStyle.Dash,
                Color(getColorArgb(com.esri.arcgismaps.sample.sampleslib.R.color.colorPrimary)),
                3f
            )
        )

        // create a graphic (solid) to represent the route that's been traveled (initially empty)
        routeTraveledGraphic = Graphic(
            routeGeometry,
            SimpleLineSymbol(
                SimpleLineSymbolStyle.Solid,
                Color.cyan,
                3f
            )
        )

        val stopGraphics = routeStops.map {
            Graphic(
                geometry = it.geometry,
                symbol = SimpleMarkerSymbol(
                    style = SimpleMarkerSymbolStyle.Circle,
                    color = Color.red,
                    size = 10f
                )
            )
        }

        // add the graphics to the mapView's graphics overlays
        graphicsOverlay.graphics.addAll(
            listOf(routeAheadGraphic, routeTraveledGraphic) + stopGraphics
        )
    }

    /**
     * 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.setViewpoint(Viewpoint(it.extent))
            }
            mapViewProxy.setViewpointRotation(0.0)
            createRouteGraphics()

            isNavigateButtonEnabled = true
        }
    }

    /**
     * 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 = getString(R.string.next_direction) + " " + voiceGuidance.text
        }
    }

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

    private fun getString(id: Int): String {
        return getApplication<Application>().resources.getString(id)
    }

    private fun getStringArray(id: Int): Array<out String> {
        return getApplication<Application>().resources.getStringArray(id)
    }

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

    fun setLocationDisplay(locationDisplay: LocationDisplay) {
        this.locationDisplay = locationDisplay
    }
}

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