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
/* Copyright 2023 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
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.text.format.DateUtils
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.arcgismaps.ApiKey
import com.arcgismaps.ArcGISEnvironment
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.view.Graphic
import com.arcgismaps.mapping.view.GraphicsOverlay
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.esri.arcgismaps.sample.navigateroute.databinding.ActivityMainBinding
import com.google.android.material.button.MaterialButton
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
import com.esri.arcgismaps.sample.sampleslib.*
import java.time.Instant
import java.util.concurrent.atomic.AtomicBoolean
class MainActivity : AppCompatActivity() {
// set up data binding for the activity
private val activityMainBinding: ActivityMainBinding by lazy {
DataBindingUtil.setContentView(this, R.layout.activity_main)
}
private val mapView by lazy {
activityMainBinding.mapView
}
private val resetNavigationButton: MaterialButton by lazy {
activityMainBinding.resetNavigationButton
}
private val recenterButton: MaterialButton by lazy {
activityMainBinding.recenterButton
}
private val distanceRemainingTextView: TextView by lazy {
activityMainBinding.distanceRemainingTextView
}
private val timeRemainingTextView: TextView by lazy {
activityMainBinding.timeRemainingTextView
}
private val nextDirectionTextView: TextView by lazy {
activityMainBinding.nextDirectionTextView
}
private val nextStopTextView: TextView by lazy {
activityMainBinding.nextStopTextView
}
/**
* Destination list of stops for the RouteParameters
*/
private val routeStops by lazy {
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()))
)
}
// instance of the route ahead polyline
private var routeAheadGraphic: Graphic = Graphic()
// instance of the route traveled polyline
private var routeTraveledGraphic: Graphic = Graphic()
// instance of the MapView's graphic overlay
private val graphicsOverlay = GraphicsOverlay()
// boolean to check if Android text-speech is initialized
private var isTextToSpeechInitialized = AtomicBoolean(false)
// instance of Android text-speech
private var textToSpeech: TextToSpeech? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// authentication with an API key or named user is
// required to access basemaps and other location services
ArcGISEnvironment.apiKey = ApiKey.create(BuildConfig.API_KEY)
// some parts of the API require an Android Context to properly interact with Android system
// features, such as LocationProvider and application resources
ArcGISEnvironment.applicationContext = applicationContext
lifecycle.addObserver(mapView)
// create and add a map with a streets basemap style
val map = ArcGISMap(BasemapStyle.ArcGISStreets)
mapView.map = map
// create a graphics overlay to hold our route 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.configuration.locales[0]
isTextToSpeechInitialized.set(true)
}
}
// generate a route with directions and stops for navigation
val routeTask = RouteTask(getString(R.string.routing_service_url))
// create the default parameters and solve route
lifecycleScope.launch {
// load and set the route parameters
val routeParameters = routeTask.createDefaultParameters().getOrElse {
return@launch showError("Error creating default parameters:${it.message}")
}.apply {
setStops(routeStops)
returnDirections = true
returnStops = true
returnRoutes = true
}
// get the solved route result
val routeResult = routeTask.solveRoute(routeParameters).getOrElse {
return@launch showError("Error solving route:${it.message}")
}
// get the route geometry from the route result
val routeGeometry = routeResult.routes[0].routeGeometry
// set the map view view point to show the whole route
if (routeGeometry?.extent != null) {
mapView.setViewpoint(Viewpoint(routeGeometry.extent))
} else {
return@launch showError("Route geometry extent is null.")
}
// start navigating on app launch
startNavigation(routeResult)
}
// wire up recenter button
recenterButton.setOnClickListener {
mapView.locationDisplay.setAutoPanMode(LocationDisplayAutoPanMode.Navigation)
recenterButton.isEnabled = false
}
}
/**
* Start the navigation along the provided route using the [routeResult] and
* collects updates in the location using the MapView's location display.
* */
private fun startNavigation(routeResult: RouteResult) {
// get the route's geometry from the route result
val routeGeometry: Polyline = routeResult.routes[0].routeGeometry
?: return showError("Route is missing geometry")
// create the graphics using the route's geometry
createRouteGraphics(routeGeometry)
// 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(
routeGeometry, simulationParameters
)
// set up a RouteTracker for navigation along the calculated route
val routeTracker = RouteTracker(
routeResult,
routeIndex = 0,
skipCoincidentStops = true
).apply {
setSpeechEngineReadyCallback {
isTextToSpeechInitialized.get() && textToSpeech?.isSpeaking == false
}
}
// plays the direction voice guidance
lifecycleScope.launch {
updateVoiceGuidance(routeTracker)
}
// 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.also {
// set the simulated location data source as the location data source for this app
it.dataSource = routeTrackerLocationDataSource
it.setAutoPanMode(LocationDisplayAutoPanMode.Navigation)
}
// start the LocationDisplay, which starts the
// RouteTrackerLocationDataSource and SimulatedLocationDataSource
lifecycleScope.launch {
locationDisplay.dataSource.start().getOrElse {
showError("Error starting LocationDataSource: ${it.message} ")
}
// set the text for first destination
nextStopTextView.text = resources.getStringArray(R.array.stop_message)[0]
}
// listen for changes in location
val locationDisplayJob = lifecycleScope.launch {
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)
}
}
// listen if user navigates the map view away from the
// location display, activate the recenter button
val autoPanModeJob = lifecycleScope.launch {
locationDisplay.autoPanMode.filter { it == LocationDisplayAutoPanMode.Off }
.collect { recenterButton.isEnabled = true }
}
// reset the navigation if button is clicked
resetNavigationButton.setOnClickListener {
lifecycleScope.launch {
if (locationDisplayJob.isActive) {
// stop location data sources
locationDisplay.dataSource.stop()
// cancel the coroutine jobs
locationDisplayJob.cancelAndJoin()
autoPanModeJob.cancelAndJoin()
// start navigation again
startNavigation(routeResult)
}
}
}
}
/**
* 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
nextDirectionTextView.text = getString(R.string.next_direction, voiceGuidance.text)
}
}
/**
* 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
distanceRemainingTextView.text = getString(
R.string.distance_remaining,
remainingDistance.displayText,
remainingDistance.displayTextUnits.abbreviation
)
timeRemainingTextView.text = getString(R.string.time_remaining, remainingTimeString)
// 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 showError("Error retrieving next destination: ${it.message}")
}
// set second stop message
nextStopTextView.text = resources.getStringArray(R.array.stop_message)[1]
} else {
// the final destination has been reached,
// stop the location data source
mapView.locationDisplay.dataSource.stop()
// set last stop message
nextStopTextView.text = resources.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 [routeGeometry]
*/
private fun createRouteGraphics(routeGeometry: Polyline) {
// clear any graphics from the current graphics overlay
graphicsOverlay.graphics.clear()
// create a graphic (with a dashed line symbol) to represent the route
routeAheadGraphic = Graphic(
routeGeometry,
SimpleLineSymbol(
SimpleLineSymbolStyle.Dash,
Color(getColor(com.esri.arcgismaps.sample.sampleslib.R.color.colorPrimary)),
5f
)
)
// create a graphic (solid) to represent the route that's been traveled (initially empty)
routeTraveledGraphic = Graphic(
routeGeometry,
SimpleLineSymbol(
SimpleLineSymbolStyle.Solid,
Color.red,
5f
)
)
// add the graphics to the mapView's graphics overlays
mapView.graphicsOverlays[0].graphics.addAll(
listOf(
routeAheadGraphic,
routeTraveledGraphic
)
)
}
private fun showError(message: String) {
Log.e(localClassName, message)
Snackbar.make(mapView, message, Snackbar.LENGTH_SHORT).show()
}
}