Navigate route

View inJavaKotlinView 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.createDefaultParametersAsync().
  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.solveAsync(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. Add a listener to capture TrackingStatusChangedEvents, and then get the TrackingStatus 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.
  9. Add a NewVoiceGuidanceListener 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.
  10. You can also query the tracking status for the current DirectionManeuver index, retrieve that maneuver from the Route and get it's direction text to display in the GUI.
  11. To establish whether the destination has been reached, get the DestinationStatus from the tracking status. If the destination status is 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
  • ReroutingStrategy
  • 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.

Tags

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

Sample Code

MainActivity.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
/*
 *  Copyright 2020 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.arcgisruntime.sample.navigateroute

import android.content.res.Resources
import android.graphics.Color
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.text.format.DateUtils
import android.util.Log
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.location.RouteTrackerLocationDataSource
import com.esri.arcgisruntime.location.SimulatedLocationDataSource
import com.esri.arcgisruntime.location.SimulationParameters
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.LocationDisplay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.navigation.DestinationStatus
import com.esri.arcgisruntime.navigation.ReroutingParameters
import com.esri.arcgisruntime.navigation.RouteTracker
import com.esri.arcgisruntime.navigation.TrackingStatus
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
import com.esri.arcgisruntime.tasks.networkanalysis.RouteParameters
import com.esri.arcgisruntime.tasks.networkanalysis.RouteResult
import com.esri.arcgisruntime.tasks.networkanalysis.RouteTask
import com.esri.arcgisruntime.tasks.networkanalysis.Stop
import com.esri.arcgisruntime.sample.navigateroute.databinding.ActivityMainBinding
import java.util.Calendar
import java.util.concurrent.ExecutionException

class MainActivity : AppCompatActivity() {

    private val TAG: String = this::class.java.simpleName

    private var textToSpeech: TextToSpeech? = null

    private var isTextToSpeechInitialized = false

    private val activityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    private val mapView: MapView by lazy {
        activityMainBinding.mapView
    }

    private val navigateRouteButton: Button by lazy {
        activityMainBinding.navigationControls.navigateRouteButton
    }

    private val recenterButton: Button by lazy {
        activityMainBinding.navigationControls.recenterButton
    }

    private val distanceRemainingTextView: TextView by lazy {
        activityMainBinding.navigationControls.distanceRemainingTextView
    }

    private val timeRemainingTextView: TextView by lazy {
        activityMainBinding.navigationControls.timeRemainingTextView
    }

    private val nextDirectionTextView: TextView by lazy {
        activityMainBinding.navigationControls.nextDirectionTextView
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(activityMainBinding.root)

        // authentication with an API key or named user is required to access basemaps and other
        // location services
        ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)

        // create a map and set it to the map view
        mapView.map = ArcGISMap(BasemapStyle.ARCGIS_STREETS)

        // create a graphics overlay to hold our route graphics and clear any graphics
        mapView.graphicsOverlays.add(GraphicsOverlay())

        // create text-to-speech to replay navigation voice guidance
        textToSpeech = TextToSpeech(this) { status ->
            if (status != TextToSpeech.ERROR) {
                textToSpeech?.language = Resources.getSystem()
                    .configuration.locale
                isTextToSpeechInitialized = true
            }
        }

        // generate a route with directions and stops for navigation
        val routeTask = RouteTask(this, getString(R.string.routing_service_url))
        val routeParametersFuture = routeTask.createDefaultParametersAsync()
        routeParametersFuture.addDoneListener {

            // define the route parameters
            val routeParameters = routeParametersFuture.get().apply {
                try {
                    setStops(routeStops)
                    isReturnDirections = true
                    isReturnStops = true
                    isReturnRoutes = true
                } catch (e: Exception) {
                    when (e) {
                        is InterruptedException, is ExecutionException -> {
                            val error = "Error getting the default route parameters: " + e.message
                            Toast.makeText(this@MainActivity, error, Toast.LENGTH_LONG).show()
                            Log.e(TAG, error)
                        }
                        else -> throw e
                    }
                }
            }

            val routeResultFuture = routeTask.solveRouteAsync(routeParameters)
            routeResultFuture.addDoneListener {
                try {
                    // get the route geometry from the route result
                    val routeResult = routeResultFuture.get()
                    val routeGeometry = routeResult.routes[0].routeGeometry
                    // create a graphic for the route geometry
                    val routeGraphic = Graphic(
                        routeGeometry,
                        SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLUE, 5f)
                    )
                    // add it to the graphics overlay
                    mapView.graphicsOverlays[0].graphics.add(routeGraphic)
                    // set the map view view point to show the whole route
                    mapView.setViewpointAsync(Viewpoint(routeGeometry.extent))

                    // set button to start navigation with the given route
                    navigateRouteButton.setOnClickListener {
                        startNavigation(
                            routeTask,
                            routeParameters,
                            routeResult
                        )
                    }

                    // start navigating
                    startNavigation(routeTask, routeParameters, routeResult)
                } catch (e: Exception) {
                    when (e) {
                        is InterruptedException, is ExecutionException -> {
                            val error = "Error creating the route result: " + e.message
                            Toast.makeText(this, error, Toast.LENGTH_LONG).show()
                            Log.e(TAG, error)
                        }
                        else -> throw e
                    }
                }
            }
        }

        // wire up recenter button
        recenterButton.apply {
            isEnabled = false
            setOnClickListener {
                mapView.locationDisplay.autoPanMode = LocationDisplay.AutoPanMode.NAVIGATION
                recenterButton.isEnabled = false
            }
        }
    }

    /**
     * Start the navigation along the provided route.
     *
     * @param routeTask used to generate the route.
     * @param routeParameters to describe the route.
     * @param routeResult solved from the routeTask.
     * */
    private fun startNavigation(
        routeTask: RouteTask,
        routeParameters: RouteParameters,
        routeResult: RouteResult
    ) {

        // clear any graphics from the current graphics overlay
        mapView.graphicsOverlays[0].graphics.clear()

        // get the route's geometry from the route result
        val routeGeometry = routeResult.routes[0].routeGeometry
        // create a graphic (with a dashed line symbol) to represent the route
        val routeAheadGraphic = Graphic(
            routeGeometry,
            SimpleLineSymbol(SimpleLineSymbol.Style.DASH, Color.MAGENTA, 5f)
        )
        // create a graphic (solid) to represent the route that's been traveled (initially empty)
        val routeTraveledGraphic = Graphic(
            routeGeometry,
            SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLUE, 5f)
        )
        // add the graphics to the mapView's graphics overlays
        mapView.graphicsOverlays[0].graphics.addAll(listOf(routeAheadGraphic, routeTraveledGraphic))

        // set up a simulated location data source which simulates movement along the route
        val simulationParameters = SimulationParameters(Calendar.getInstance(), 35.0, 5.0, 5.0)
        val simulatedLocationDataSource = SimulatedLocationDataSource().apply {
            setLocations(routeGeometry, simulationParameters)
        }

        // set up a RouteTracker for navigation along the calculated route
        val reroutingParameters = ReroutingParameters(routeTask, routeParameters)
        val routeTracker = RouteTracker(applicationContext, routeResult, 0, true).apply {
            enableReroutingAsync(reroutingParameters)
        }

        // create a route tracker location data source to snap the location display to the route
        val routeTrackerLocationDataSource =
            RouteTrackerLocationDataSource(routeTracker, simulatedLocationDataSource)
        // get the map view's location display and set it up
        val locationDisplay = mapView.locationDisplay.apply {
            // set the simulated location data source as the location data source for this app
            locationDataSource = routeTrackerLocationDataSource
            autoPanMode = LocationDisplay.AutoPanMode.NAVIGATION
            // if the user navigates the map view away from the location display, activate the recenter button
            addAutoPanModeChangedListener { recenterButton.isEnabled = true }
        }

        // listen for changes in location
        locationDisplay.addLocationChangedListener {
            // get the route's tracking status
            val trackingStatus = routeTracker.trackingStatus
            // set geometries for the route ahead and the remaining route
            routeAheadGraphic.geometry = trackingStatus.routeProgress.remainingGeometry
            routeTraveledGraphic.geometry = trackingStatus.routeProgress.traversedGeometry

            // get remaining distance information
            val remainingDistance: TrackingStatus.Distance =
                trackingStatus.destinationProgress.remainingDistance
            // covert remaining minutes to hours:minutes:seconds
            val remainingTimeString = DateUtils
                .formatElapsedTime((trackingStatus.destinationProgress.remainingTime * 60).toLong())

            // update text views
            distanceRemainingTextView.text = getString(
                R.string.distance_remaining, remainingDistance.displayText,
                remainingDistance.displayTextUnits.pluralDisplayName
            )
            timeRemainingTextView.text = getString(R.string.time_remaining, remainingTimeString)

            // listen for new voice guidance events
            routeTracker.addNewVoiceGuidanceListener { newVoiceGuidanceEvent ->
                // use Android's text to speech to speak the voice guidance
                speakVoiceGuidance(newVoiceGuidanceEvent.voiceGuidance.text)
                nextDirectionTextView.text = getString(
                    R.string.next_direction,
                    newVoiceGuidanceEvent.voiceGuidance.text
                )
            }

            // 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 (routeTracker.trackingStatus.remainingDestinationCount > 1) {
                    // switch to the next destination
                    routeTracker.switchToNextDestinationAsync()
                    Toast.makeText(
                        this,
                        "Navigating to the second stop, the Fleet Science Center.",
                        Toast.LENGTH_LONG
                    ).show()
                } else {
                    // the final destination has been reached, stop the simulated location data source
                    simulatedLocationDataSource.stop()
                    routeTrackerLocationDataSource.stop()
                    Toast.makeText(this, "Arrived at the final destination.", Toast.LENGTH_LONG)
                        .show()
                }
            }
        }
        // start the LocationDisplay, which starts the RouteTrackerLocationDataSource and SimulatedLocationDataSource
        locationDisplay.startAsync()
        Toast.makeText(
            this,
            "Navigating to the first stop, the USS San Diego Memorial.",
            Toast.LENGTH_LONG
        ).show()
    }

    /**
     * Uses Android's text to speak to say the latest voice guidance from the RouteTracker out loud.
     *
     * @param voiceGuidanceText to be converted to speech
     */
    private fun speakVoiceGuidance(voiceGuidanceText: String) {
        if (isTextToSpeechInitialized && textToSpeech?.isSpeaking == false) {
            textToSpeech?.speak(voiceGuidanceText, TextToSpeech.QUEUE_FLUSH, null, null)
        }
    }

    override fun onResume() {
        super.onResume()
        mapView.resume()
    }

    override fun onPause() {
        mapView.pause()
        super.onPause()
    }

    override fun onDestroy() {
        mapView.dispose()
        super.onDestroy()
    }
}

private val routeStops by lazy {
    listOf(
        // San Diego Convention Center
        Stop(Point(-117.160386, 32.706608, SpatialReferences.getWgs84())),
        // USS San Diego Memorial
        Stop(Point(-117.173034, 32.712327, SpatialReferences.getWgs84())),
        // RH Fleet Aerospace Museum
        Stop(Point(-117.147230, 32.730467, SpatialReferences.getWgs84()))
    )
}

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