Skip to content
View on GitHub

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" to simulate traveling and to receive directions from a preset starting point to a preset destination. Tap "Reset" to start the simulation from the beginning.

How it works

  1. Create an RouteTask using a URL to an online route service.
  2. Generate default RouteParameters using RouteTask.makeDefaultParameters().
  3. Set returnsRoutes, returnsStops, and returnsDirections on the parameters to true.
  4. Assign all Stop objects to the route parameters using RouteParameters.setStops(_:).
  5. Solve the route using RouteTask.solveRoute(using:) to get a RouteResult.
  6. Create an RouteTracker using the route result, and the index of the desired route to take.
  7. Create a RouteTrackerLocationDataSource with the route tracker and a SimulatedLocationDataSource object to snap the location display to the route.
  8. Use RouteTracker.trackingStatus to be notified of TrackingStatus changes, and use them to display updated route information. TrackingStatus includes a variety of information on the route progress, such as the remaining distance, remaining geometry or traversed geometry (represented by an Polyline), or the remaining time (TimeInterval), amongst others.
  9. Use RouteTracker.voiceGuidances to be notified of new voice guidances. From the voice guidance, get the VoiceGuidance.text 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 its 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, 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

  • DestinationStatus
  • DirectionManeuver
  • Location
  • LocationDataSource
  • Route
  • RouteParameters
  • RouteTask
  • RouteTracker
  • RouteTrackerLocationDataSource
  • SimulatedLocationDataSource
  • Stop
  • VoiceGuidance

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

NavigateRouteView.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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 // 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 // // 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 AVFAudio import SwiftUI  struct NavigateRouteView: View {  /// The view model for this sample.  @StateObject private var model = Model()   var body: some View {  MapView(  map: model.map,  viewpoint: model.viewpoint,  graphicsOverlays: model.graphicsOverlays  )  .onViewpointChanged(kind: .centerAndScale) { model.viewpoint = $0 }  .locationDisplay(model.locationDisplay)  .errorAlert(presentingError: $model.error)  .overlay(alignment: .top) {  Text(model.statusText)  .frame(maxWidth: .infinity, alignment: .leading)  .padding(8)  .background(.thinMaterial, ignoresSafeAreaEdges: .horizontal)  }  .task {  // Solves the route and sets the navigation.  await model.solveRoute()  model.setNavigation()  }  .toolbar {  ToolbarItemGroup(placement: .bottomBar) {  Button("Navigate") {  model.isNavigatingRoute = true  }  .task(id: model.isNavigatingRoute) {  guard model.isNavigatingRoute else { return }  await model.startNavigation()  }  .disabled(model.isNavigateDisabled || model.isNavigatingRoute)   Spacer()   Button("Recenter") {  model.autoPanMode = .navigation  }  .disabled(!model.isNavigatingRoute || model.autoPanMode == .navigation)   Spacer()   Button("Reset") {  Task {  await model.resetNavigation()  model.isNavigatingRoute = false  }  }  .disabled(model.isResettingRoute)  }  }  } }  private extension NavigateRouteView {  /// A view model for this sample.  @MainActor  class Model: ObservableObject {  /// A Boolean value indicating whether the navigate button is disabled.  @Published var isNavigateDisabled = true   /// A Boolean value indicating whether the sample is navigating the route.  @Published var isNavigatingRoute = false   /// A Boolean value indicating whether navigation is being reset.  @Published var isResettingRoute = false   /// The error shown in the error alert.  @Published var error: Error?   /// The viewpoint of the map.  @Published var viewpoint: Viewpoint?   /// The current auto-pan mode.  @Published var autoPanMode: LocationDisplay.AutoPanMode {  didSet {  locationDisplay.autoPanMode = autoPanMode  }  }   /// The status text to display to the user.  @Published var statusText: String = defaultStatus   /// A map with a navigation basemap style.  let map = Map(basemapStyle: .arcGISNavigation)   /// The map's location display.  let locationDisplay = LocationDisplay()   /// The default status to display when not navigating.  static let defaultStatus = "Directions are shown here."   /// The route task.  private let routeTask = RouteTask(url: .routeTask)   /// The route result.  private var routeResult: RouteResult?   /// The route tracker.  private var routeTracker: RouteTracker!   /// The directions for the route.  private var directions: [DirectionManeuver] = []   /// An AVSpeechSynthesizer for text to speech.  private let speechSynthesizer = AVSpeechSynthesizer()   /// The graphics overlay for the stops.  private let stopGraphicsOverlay: GraphicsOverlay   /// The graphics overlay for the route.  private let routeGraphicsOverlay: GraphicsOverlay   /// Formats the time remaining for display.  private let timeFormatter: DateComponentsFormatter = {  let formatter = DateComponentsFormatter()  formatter.allowedUnits = [.hour, .minute, .second]  formatter.unitsStyle = .full  return formatter  }()   /// The map's graphics overlays.  var graphicsOverlays: [GraphicsOverlay] {  return [stopGraphicsOverlay, routeGraphicsOverlay]  }   /// A graphic of the route remaining.  private let routeRemainingGraphic: Graphic   /// A graphic of the route traversed.  private let routeTraversedGraphic: Graphic   init() {  autoPanMode = .off   // Creates the graphics for each stop.  let stopGraphics = Self.stops.map {  Graphic(  geometry: $0.geometry,  symbol: SimpleMarkerSymbol(style: .diamond, color: .orange, size: 20)  )  }   // Creates the graphics for the route remaining and traversed.  routeRemainingGraphic = Graphic(symbol: SimpleLineSymbol(style: .dash, color: .systemPurple, width: 5))  routeTraversedGraphic = Graphic(symbol: SimpleLineSymbol(style: .solid, color: .systemBlue, width: 3))   // Creates the graphics overlay for the stops and route.  stopGraphicsOverlay = GraphicsOverlay(graphics: stopGraphics)  routeGraphicsOverlay = GraphicsOverlay(graphics: [routeRemainingGraphic, routeTraversedGraphic])  }   /// Solves the route.  func solveRoute() async {  do {  // Creates the default parameters from the route task.  let parameters = try await routeTask.makeDefaultParameters()   // Configures the parameters.  parameters.returnsDirections = true  parameters.returnsStops = true  parameters.returnsRoutes = true  parameters.outputSpatialReference = .wgs84   // Sets the stops on the parameters.  parameters.setStops(Self.stops)   // Solves the route based on the parameters.  routeResult = try await routeTask.solveRoute(using: parameters)   // Enables the navigate button.  isNavigateDisabled = false  } catch {  self.error = error  }  }   /// Sets the route tracker and location display's data source with a solved route. Updates  /// the list of directions, the route ahead graphic, and the map's viewpoint.  func setNavigation() {  guard let routeResult else { return }   // Creates a route tracker from the route results.  routeTracker = RouteTracker(routeResult: routeResult, routeIndex: 0, skipsCoincidentStops: true)  guard let routeTracker else { return }   routeTracker.voiceGuidanceUnitSystem = Locale.current.measurementSystem == .us  ? .imperial  : .metric   // Gets the route and its geometry from the route result.  guard let firstRoute = routeResult.routes.first,  let routeGeometry = firstRoute.geometry else {  return  }   // Updates the directions.  directions = firstRoute.directionManeuvers   // Creates the mock data source from the route's geometry.  let densifiedRoute = GeometryEngine.geodeticDensify(  routeGeometry,  maxSegmentLength: 50,  lengthUnit: .meters,  curveType: .geodesic  ) as! Polyline  let mockDataSource = SimulatedLocationDataSource(polyline: densifiedRoute)   // Creates a route tracker location data source.  let routeTrackerLocationDataSource = RouteTrackerLocationDataSource(  routeTracker: routeTracker,  locationDataSource: mockDataSource  )   // Sets the location display's data source.  locationDisplay.dataSource = routeTrackerLocationDataSource   // Updates the graphics and viewpoint.  routeRemainingGraphic.geometry = routeGeometry  viewpoint = Viewpoint(boundingGeometry: routeGeometry, rotation: 0)  }   /// Starts monitoring multiple asynchronous streams of information.  private func startTracking() async {  await withTaskGroup(of: Void.self) { group in  group.addTask { await self.trackAutoPanMode() }  group.addTask { await self.trackStatus() }  group.addTask { await self.trackVoiceGuidance() }  }  }   /// Monitors the asynchronous stream of tracking statuses.  ///  /// When new statuses are delivered, update the route's traversed and remaining graphics.  private func trackStatus() async {  for await status in routeTracker.$trackingStatus {  if let status {  routeTraversedGraphic.geometry = status.routeProgress.traversedGeometry  routeRemainingGraphic.geometry = status.routeProgress.remainingGeometry   switch status.destinationStatus {  case .notReached, .approaching:  statusText = """  Distance remaining: \(status.routeProgress.remainingDistance.distanceRemainingText)  Time remaining: \(timeFormatter.string(from: status.routeProgress.remainingTime)!)  """  if status.currentManeuverIndex + 1 < directions.count {  statusText.append("\nNext direction: \(directions[status.currentManeuverIndex + 1].text)")  }  case .reached:  if status.remainingDestinationCount > 1 {  statusText = "Intermediate stop reached, continue to next stop."  try? await routeTracker.switchToNextDestination()  } else {  await locationDisplay.dataSource.stop()  }  @unknown default:  break  }  }  }  }   /// Monitors the asynchronous stream of voice guidances.  private func trackVoiceGuidance() async {  for await voiceGuidance in routeTracker.voiceGuidances {  speechSynthesizer.stopSpeaking(at: .word)  speechSynthesizer.speak(AVSpeechUtterance(string: voiceGuidance.text))  }  }   /// Monitors the asynchronous stream of auto-pan modes.  ///  /// Updates the current auto-pan mode if it does not match the location display's auto-pan  /// mode.  private func trackAutoPanMode() async {  for await mode in locationDisplay.$autoPanMode {  if autoPanMode != mode {  autoPanMode = mode  }  }  }   /// Starts navigating the route.  func startNavigation() async {  do {  try await locationDisplay.dataSource.start()  locationDisplay.autoPanMode = .navigation  await startTracking()  } catch {  self.error = error  }  }   /// Resets relevant stateful properties.  func resetNavigation() async {  guard !isResettingRoute else { return }  isResettingRoute = true  locationDisplay.autoPanMode = .off  await locationDisplay.dataSource.stop()  setNavigation()  routeTraversedGraphic.geometry = nil  speechSynthesizer.stopSpeaking(at: .immediate)  statusText = Self.defaultStatus  isResettingRoute = false  }  } }  private extension NavigateRouteView.Model {  /// The stops for this sample.  static var stops: [Stop] {  let one = Stop(point: Point(x: -117.160386727, y: 32.706608, spatialReference: .wgs84))  one.name = "San Diego Convention Center"  let two = Stop(point: Point(x: -117.173034, y: 32.712329, spatialReference: .wgs84))  two.name = "USS San Diego Memorial"  let three = Stop(point: Point(x: -117.147230, y: 32.730467, spatialReference: .wgs84))  three.name = "RH Fleet Aerospace Museum"  return [one, two, three]  } }  private extension TrackingDistance {  var distanceRemainingText: String {  "\(displayText) \(self.displayTextUnits.abbreviation)"  } }  private extension URL {  /// The URL for the route task.  static var routeTask: URL {  URL(string: "http://sampleserver7.arcgisonline.com/server/rest/services/NetworkAnalysis/SanDiego/NAServer/Route")!  } }  #Preview {  NavigationStack {  NavigateRouteView()  } }

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