Navigate route with rerouting

View on GitHub

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 the play button 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 the recenter button to reposition the viewpoint. Tap the reset button to start the simulation from the beginning.

How it works

  1. Create a RouteTask using local network data.
  2. Generate default RouteParameters using RouteTask.makeDefaultParameters().
  3. Set returnsStops and returnsDirections on the parameters to true.
  4. Add Stops to the parameters' stops array using RouteParameters.setStops(_:).
  5. Solve the route using RouteTask.solveRoute(using:) to get a RouteResult.
  6. Create a RouteTracker using the route result and the index of the desired route to take.
  7. Enable rerouting on the route tracker with RouteTracker.enableRerouting(using:).
  8. Use RouteTracker.$trackingStatus to display updated route information and update the route graphics. 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 (TimeInterval), amongst others.
  9. You can also query the tracking status for the current DirectionManeuver index, retrieve that maneuver from the Route, and get its direction text to display.
  10. Use RouteTracker.voiceGuidances to get the VoiceGuidance whenever new instructions are available. From the voice guidance, get the text 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 reached, and the remainingDestinationCount is 1, you 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
  • DirectionManeuver
  • Location
  • LocationDataSource
  • ReroutingStrategy
  • Route
  • RouteParameters
  • RouteTask
  • RouteTracker
  • Stop
  • VoiceGuidance

Offline data

The SanDiegoTourPath JSON file 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

NavigateRouteWithReroutingView.swiftNavigateRouteWithReroutingView.swiftNavigateRouteWithReroutingView.Model.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
// 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
//
//   https://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 ArcGIS
import SwiftUI

struct NavigateRouteWithReroutingView: View {
    /// The view model for the sample.
    @StateObject private var model = Model()

    /// The navigation action currently being run.
    @State private var selectedNavigationAction: NavigationAction? = .setUp

    /// A Boolean value indicating whether the navigation can be reset.
    @State private var canReset = false

    /// The error shown in the error alert.
    @State private var error: Error?

    var body: some View {
        MapView(
            map: model.map,
            viewpoint: model.viewpoint,
            graphicsOverlays: [model.graphicsOverlay]
        )
        .onViewpointChanged(kind: .centerAndScale) { model.viewpoint = $0 }
        .locationDisplay(model.locationDisplay)
        .overlay(alignment: .top) {
            Text(model.statusMessage)
                .frame(maxWidth: .infinity, alignment: .center)
                .padding(8)
                .background(.thinMaterial, ignoresSafeAreaEdges: .horizontal)
        }
        .toolbar {
            ToolbarItemGroup(placement: .bottomBar) {
                Button {
                    selectedNavigationAction = .reset
                } label: {
                    Image(systemName: "gobackward")
                }
                .disabled(!canReset)

                Spacer()
                Button {
                    selectedNavigationAction = model.isNavigating ? .stop : .start
                } label: {
                    Image(systemName: model.isNavigating ? "pause.fill" : "play.fill")
                }
                .disabled(
                    selectedNavigationAction == .setUp
                    || model.routeTracker.trackingStatus?.destinationStatus == .reached
                )

                Spacer()
                Button {
                    model.locationDisplay.autoPanMode = .navigation
                } label: {
                    Image(systemName: "location.fill")
                }
                .disabled(!model.isNavigating || model.locationDisplay.autoPanMode == .navigation)
            }
        }
        .task(id: selectedNavigationAction) {
            guard let selectedNavigationAction else { return }
            defer { self.selectedNavigationAction = nil }

            do {
                // Run the new action.
                switch selectedNavigationAction {
                case .setUp:
                    try await model.setUp()

                case .start:
                    try await model.start()
                    canReset = true

                case .stop:
                    await model.stop()

                case .reset:
                    try await model.reset()
                    canReset = false
                }
            } catch {
                self.error = error
            }
        }
        .task(id: model.isNavigating) {
            guard model.isNavigating, let routeTracker = model.routeTracker else { return }

            await withTaskGroup(of: Void.self) { group in
                group.addTask {
                    // Handle new tracking statuses from the route tracker.
                    for await trackingStatus in routeTracker.$trackingStatus {
                        guard let trackingStatus else { continue }
                        await model.updateProgress(using: trackingStatus)
                    }
                }

                group.addTask {
                    // Speak new voice guidances from the route tracker.
                    for await voiceGuidance in routeTracker.voiceGuidances {
                        await model.speakVoiceGuidance(voiceGuidance)
                    }
                }
            }
        }
        .errorAlert(presentingError: $error)
    }
}

private extension NavigateRouteWithReroutingView {
    /// An enumeration representing an action relating to the navigation.
    enum NavigationAction {
        /// Set up the route.
        case setUp
        /// Start navigating.
        case start
        /// Stop navigating.
        case stop
        /// Reset the route.
        case reset
    }
}

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