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 an AGSRouteTask using local network data.
  2. Generate default AGSRouteParameters using AGSRouteTask.defaultRouteParameters(completion:).
  3. Set returnRoutes, returnStops, and returnDirections on the parameters to true.
  4. Add AGSStops to the parameters' array of stops using AGSRouteParameters.setStops(_:).
  5. Solve the route using AGSRouteTask.solveRoute(with:completion:) to get an AGSRouteResult.
  6. Create an AGSRouteTracker using the route result, and the index of the desired route to take.
  7. Enable rerouting in the route tracker using AGSRouteTracker.enableRerouting(with:routeParameters:strategy:visitFirstStopOnStart:completion:). Pass AGSReroutingStrategy.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. Implement AGSLocationChangeHandlerDelegate.locationDataSource(_:locationDidChange:) to track the location of the device and update the route tracking status.
  9. Implement AGSRouteTrackerDelegate.routeTracker(_:didUpdate:) to be notified of AGSTrackingStatus changes, and use them to display updated route information. AGSTrackingStatus includes a variety of information on the route progress, such as the remaining distance, remaining geometry or traversed geometry (represented by an AGSPolyline), or the remaining time (Double), amongst others.
  10. Implement AGSRouteTrackerDelegate.routeTracker(_:didGenerateNewVoiceGuidance:) to be notified of new voice guidances. From the voice guidance, get the AGSVoiceGuidance.text representing the directions and use a text-to-speech engine to output the maneuver directions.
  11. You can also query the tracking status for the current AGSDirectionManeuver index by retrieving that maneuver from the AGSRoute and getting its direction text to display in the GUI.
  12. 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, you have arrived at the destination and can stop routing. If there are several destinations on your route and the remaining destination count is greater than 1, switch the route tracker to the next destination.

Relevant API

  • AGSDestinationStatus
  • AGSDirectionManeuver
  • AGSLocation
  • AGSLocationDataSource
  • AGSReroutingStrategy
  • AGSRoute
  • AGSRouteParameters
  • AGSRouteTask
  • AGSRouteTracker
  • AGSRouteTrackerLocationDataSource
  • AGSSimulatedLocationDataSource
  • AGSStop
  • AGSVoiceGuidance

Offline data

The Navigate a Route GPX Track provides a simulated path for the device to demonstrate routing while traveling.

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

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

NavigateRouteWithReroutingViewController.swift
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
// 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.

import UIKit
import AVFoundation
import ArcGIS

class NavigateRouteWithReroutingViewController: UIViewController {
    // MARK: Storyboard views

    /// The label to display navigation status.
    @IBOutlet var statusLabel: UILabel!
    /// The button to start navigation.
    @IBOutlet var navigateBarButtonItem: UIBarButtonItem!
    /// The button to reset navigation.
    @IBOutlet var resetBarButtonItem: UIBarButtonItem!
    /// The button to recenter the map to navigation pan mode.
    @IBOutlet var recenterBarButtonItem: UIBarButtonItem!
    /// The map view managed by the view controller.
    @IBOutlet var mapView: AGSMapView! {
        didSet {
            mapView.map = AGSMap(basemapStyle: .arcGISNavigation)
            mapView.graphicsOverlays.add(makeRouteOverlay())
        }
    }

    // MARK: Instance properties

    /// The route task to solve the route between stops, using the online routing service.
    let routeTask = AGSRouteTask(fileURLToDatabase: Bundle.main.url(forResource: "sandiego", withExtension: "geodatabase", subdirectory: "san-diego")!, networkName: "Streets_ND")
    /// The route result solved by the route task.
    var routeResult: AGSRouteResult!
    /// The route tracker for navigation. Use delegate methods to update tracking status.
    var routeTracker: AGSRouteTracker!
    /// The parameters of the route tracker.
    var routeParameters: AGSRouteParameters!
    /// A list to keep track of directions solved by the route task.
    var directionManeuvers: [AGSDirectionManeuver] = []
    /// The graphic (with a dashed line symbol) to represent the route ahead.
    let routeAheadGraphic = AGSGraphic(geometry: nil, symbol: AGSSimpleLineSymbol(style: .dash, color: .systemPurple, width: 5))
    /// The graphic to represent the route that's been traveled (initially empty).
    let routeTraveledGraphic = AGSGraphic(geometry: nil, symbol: AGSSimpleLineSymbol(style: .solid, color: .systemBlue, width: 3))
    /// The original view point that can be reset later on.
    var defaultViewPoint: AGSViewpoint?
    /// The starting location, the San Diego Convention Center.
    let startLocation = AGSPoint(x: -117.160386727, y: 32.706608, spatialReference: .wgs84())
    /// The destination location, the Fleet Science Center.
    let destinationLocation = AGSPoint(x: -117.146679, y: 32.730351, spatialReference: .wgs84())
    /// The location data source provided by a local GPX file.
    var gpxDataSource: AGSGPXLocationDataSource?

    /// A formatter to format a time value into human readable string.
    let timeFormatter: DateComponentsFormatter = {
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.hour, .minute, .second]
        formatter.unitsStyle = .full
        return formatter
    }()
    /// An AVSpeechSynthesizer for text to speech.
    let speechSynthesizer = AVSpeechSynthesizer()

    // MARK: Actions

    /// Called in response to the "Navigate" button being tapped.
    @IBAction func startNavigation() {
        navigateBarButtonItem.isEnabled = false
        resetBarButtonItem.isEnabled = true
        // Start the location data source and location display.
        mapView.locationDisplay.start()
    }

    /// Called in response to the "Reset" button being tapped.
    @IBAction func reset() {
        // Stop the speech, if there is any.
        speechSynthesizer.stopSpeaking(at: .immediate)
        // Set the initial location.
        guard let initialLocation = gpxDataSource?.locations?.first else { return }
        // Reset to the starting location for location display.
        mapView.locationDisplay.dataSource.didUpdate(initialLocation)
        // Stop the location display as well as datasource generation, if reset before the end is reached.
        mapView.locationDisplay.stop()
        mapView.locationDisplay.autoPanModeChangedHandler = nil
        mapView.locationDisplay.autoPanMode = .off
        directionManeuvers.removeAll()
        setStatus(message: "Directions are shown here.")

        // Reset the navigation.
        setNavigation(with: routeResult)
        // Reset buttons state.
        resetBarButtonItem.isEnabled = false
        navigateBarButtonItem.isEnabled = true
    }

    /// Called in response to the "Recenter" button being tapped.
    @IBAction func recenter() {
        mapView.locationDisplay.autoPanMode = .navigation
        recenterBarButtonItem.isEnabled = false
        mapView.locationDisplay.autoPanModeChangedHandler = { [weak self] _ in
            DispatchQueue.main.async {
                guard let self = self else { return }
                self.recenterBarButtonItem.isEnabled = true
                self.mapView.locationDisplay.autoPanModeChangedHandler = nil
            }
        }
    }

    // MARK: Instance methods

    /// A wrapper function for operations after the route is solved by an `AGSRouteTask`.
    ///
    /// - Parameter result: The result of the solve route operation.
    func didSolveRoute(with result: Result<AGSRouteResult, Error>) {
        switch result {
        case .success(let routeResult):
            self.routeResult = routeResult
            setNavigation(with: routeResult)
            navigateBarButtonItem.isEnabled = true
        case .failure(let error):
            presentAlert(error: error)
            setStatus(message: "Failed to solve route.")
            navigateBarButtonItem.isEnabled = false
        }
    }

    /// Make a graphics overlay with graphics.
    ///
    /// - Returns: A new `AGSGraphicsOverlay` object.
    func makeRouteOverlay() -> AGSGraphicsOverlay {
        // The graphics overlay for the polygon and points.
        let graphicsOverlay = AGSGraphicsOverlay()
        // Create a graphic for the start location.
        let startSymbol = AGSSimpleMarkerSymbol(style: .cross, color: .green, size: 25)
        let startGraphic = AGSGraphic(geometry: startLocation, symbol: startSymbol)
        // Create a graphic for the destination location.
        let destinationSymbol = AGSSimpleMarkerSymbol(style: .X, color: .red, size: 20)
        let destinationGraphic = AGSGraphic(geometry: destinationLocation, symbol: destinationSymbol)
        // Add graphics to the graphics overlay.
        graphicsOverlay.graphics.addObjects(from: [startGraphic, destinationGraphic, routeAheadGraphic, routeTraveledGraphic])
        return graphicsOverlay
    }

    /// Create the stops for the navigation.
    ///
    /// - Returns: An array of `AGSStop` objects.
    func makeStops() -> [AGSStop] {
        let stop1 = AGSStop(point: startLocation)
        stop1.name = "San Diego Convention Center"
        let stop2 = AGSStop(point: destinationLocation)
        stop2.name = "RH Fleet Aerospace Museum"
        return [stop1, stop2]
    }

    /// Make a route tracker to provide navigation information.
    ///
    /// - Parameter result: An `AGSRouteResult` object used to configure the route tracker.
    /// - Returns: An `AGSRouteTracker` object.
    func makeRouteTracker(result: AGSRouteResult) -> AGSRouteTracker {
        let tracker = AGSRouteTracker(routeResult: result, routeIndex: 0, skipCoincidentStops: true)!
        if routeTask.routeTaskInfo().supportsRerouting {
            let reroutingParameters = AGSReroutingParameters(routeTask: routeTask, routeParameters: routeParameters)!
            tracker.enableRerouting(with: reroutingParameters) { error in
                if let error = error {
                    self.presentAlert(error: error)
                }
            }
        }
        tracker.delegate = self
        tracker.voiceGuidanceUnitSystem = Locale.current.usesMetricSystem ? .metric : .imperial
        return tracker
    }

    /// Set route tracker, data source, and location display with a solved route result.
    ///
    /// - Parameter routeResult: An `AGSRouteResult` object.
    func setNavigation(with routeResult: AGSRouteResult) {
        // Set the route tracker
        routeTracker = makeRouteTracker(result: routeResult)

        // Set the mock location data source.
        let firstRoute = routeResult.routes.first!
        directionManeuvers = firstRoute.directionManeuvers
        // Create the data source from a local GPX file.
        let gpxDataSource = AGSGPXLocationDataSource(name: "navigate_a_route_detour")
        self.gpxDataSource = gpxDataSource
        // Create a route tracker location data source to snap the location display to the route.
        let routeTrackerLocationDataSource = AGSRouteTrackerLocationDataSource(routeTracker: routeTracker, locationDataSource: gpxDataSource)

        // Set location display.
        mapView.locationDisplay.dataSource = routeTrackerLocationDataSource
        recenter()

        // Update graphics and viewpoint.
        let firstRouteGeometry = firstRoute.routeGeometry!
        updateRouteGraphics(remaining: firstRouteGeometry)
        updateViewpoint(geometry: firstRouteGeometry)
    }

    /// Update the viewpoint so that it reflects the original viewpoint when the example is loaded.
    ///
    /// - Parameter result: An `AGSGeometry` object used to update the view point.
    func updateViewpoint(geometry: AGSGeometry) {
        // Show the resulting route on the map and save a reference to the route.
        if let viewPoint = defaultViewPoint {
            // Reset to initial view point with animation.
            mapView.setViewpoint(viewPoint, completion: nil)
        } else {
            mapView.setViewpointGeometry(geometry) { [weak self] _ in
                guard let self = self else { return }
                // Get the initial zoomed view point.
                self.defaultViewPoint = self.mapView.currentViewpoint(with: .centerAndScale)
            }
        }
    }

    // MARK: UI

    func setStatus(message: String) {
        statusLabel.text = message
    }

    // MARK: UIViewController

    override func viewDidLoad() {
        super.viewDidLoad()
        // Add the source code button item to the right of navigation bar.
        (navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["NavigateRouteWithReroutingViewController"]
        // Avoid the overlap between the status label and the map content.
        mapView.contentInset.top = CGFloat(statusLabel.numberOfLines) * statusLabel.font.lineHeight

        // Solve the route as map loads.
        routeTask.defaultRouteParameters { [weak self] (params: AGSRouteParameters?, error: Error?) in
            guard let self = self else { return }
            if let params = params {
                // Explicitly set values for parameters.
                params.returnDirections = true
                params.returnStops = true
                params.returnRoutes = true
                params.outputSpatialReference = .wgs84()
                params.setStops(self.makeStops())
                self.routeParameters = params
                self.routeTask.solveRoute(with: params) { [weak self] (result, error) in
                    if let result = result {
                        self?.didSolveRoute(with: .success(result))
                    } else if let error = error {
                        self?.didSolveRoute(with: .failure(error))
                    }
                }
            } else if let error = error {
                self.presentAlert(error: error)
                self.setStatus(message: "Failed to get route parameters.")
            }
        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // Reset the sample.
        reset()
    }
}

// MARK: - AGSRouteTrackerDelegate

extension NavigateRouteWithReroutingViewController: AGSRouteTrackerDelegate {
    func routeTracker(_ routeTracker: AGSRouteTracker, didGenerateNewVoiceGuidance voiceGuidance: AGSVoiceGuidance) {
        setSpeakDirection(with: voiceGuidance.text)
    }

    func routeTracker(_ routeTracker: AGSRouteTracker, didUpdate trackingStatus: AGSTrackingStatus) {
        updateTrackingStatusDisplay(routeTracker: routeTracker, status: trackingStatus)
    }

    func routeTracker(_ routeTracker: AGSRouteTracker, rerouteDidCompleteWith trackingStatus: AGSTrackingStatus?, error: Error?) {
        if let error = error {
            presentAlert(error: error)
        } else if let status = trackingStatus {
            // Get the new directions.
            directionManeuvers = status.routeResult.routes.first!.directionManeuvers
        }
    }

    func setSpeakDirection(with text: String) {
        speechSynthesizer.stopSpeaking(at: .word)
        speechSynthesizer.speak(AVSpeechUtterance(string: text))
    }

    func updateTrackingStatusDisplay(routeTracker: AGSRouteTracker, status: AGSTrackingStatus) {
        var statusText: String
        switch status.destinationStatus {
        case .notReached, .approaching:
            let distanceRemaining = status.routeProgress.remainingDistance.displayText + " " + status.routeProgress.remainingDistance.displayTextUnits.abbreviation
            let timeRemaining = timeFormatter.string(from: TimeInterval(status.routeProgress.remainingTime * 60))!
            statusText = """
            Distance remaining: \(distanceRemaining)
            Time remaining: \(timeRemaining)
            """
            if status.currentManeuverIndex + 1 < directionManeuvers.endIndex {
                let nextDirection = directionManeuvers[status.currentManeuverIndex + 1].directionText
                statusText.append("\nNext direction: \(nextDirection)")
            }
        case .reached:
            mapView.locationDisplay.stop()
            statusText = "Destination reached."
            routeAheadGraphic.geometry = nil
        default:
            statusText = "Off route!"
        }
        updateRouteGraphics(remaining: status.routeProgress.remainingGeometry, traversed: status.routeProgress.traversedGeometry)
        setStatus(message: statusText)
    }

    func updateRouteGraphics(remaining: AGSGeometry?, traversed: AGSGeometry? = nil) {
        routeAheadGraphic.geometry = remaining
        routeTraveledGraphic.geometry = traversed
    }
}

// MARK: - AGSLocationChangeHandlerDelegate

extension NavigateRouteWithReroutingViewController: AGSLocationChangeHandlerDelegate {
    func locationDataSource(_ locationDataSource: AGSLocationDataSource, locationDidChange location: AGSLocation) {
        // Update the tracker location with the new location from the simulated data source.
        routeTracker?.trackLocation(location) { [weak self] error in
            guard let self = self else { return }
            if let error = error {
                // Display error message and stop further route tracking if it
                // fails due to data format, licensing issue, etc.
                self.setStatus(message: error.localizedDescription)
                self.routeTracker = nil
            }
        }
    }
}

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