Learn how to find a route and directions with the route service A routing service is a service that uses network analysis and streets data to calculate the most effective path and turn-by-turn directions on a street network, optimize fleet routing and deliveries, find the closest facilities, calculate service areas, and more. It is hosted by Esri as the ArcGIS Routing service and can also be hosted in ArcGIS Enterprise. Learn more .

Figure : Overview of how to find a route and directions

Routing is the process of finding the path from an origin An origin is a point that defines the start of a route. Learn more to a destination A destination is a point that defines the final stop in a route. Learn more in a street network. You can use the Routing service A routing service is a service that uses network analysis and streets data to calculate the most effective path and turn-by-turn directions on a street network, optimize fleet routing and deliveries, find the closest facilities, calculate service areas, and more. It is hosted by Esri as the ArcGIS Routing service and can also be hosted in ArcGIS Enterprise. Learn more to find routes A route is a polyline that defines the best path between two or more points in a street network. Learn more , get driving directions, calculate drive times, and solve complicated, multiple vehicle routing problems. To create a route, you typically define a set of stops (origin and one or more destinations) and use the service to find a route with directions. You can also use a number of additional parameters such as barriers and mode of travel to refine the results.

In this tutorial, you define an origin and destination by clicking on the map. These values are used to get a route and directions from the route service. The directions are also displayed on the map.

Prerequisites

Before starting this tutorial:

  1. You need an ArcGIS Location Platform or ArcGIS Online account.

  2. Your system meets the system requirements.

Set up authentication

To access the secure ArcGIS location services ArcGIS Location Services, also referred to as Location Services, are services hosted by Esri that provide geospatial functionality for developing mapping applications. They include the ArcGIS Basemap Styles service, ArcGIS Static Basemap Tiles service, ArcGIS Places service, ArcGIS Geocoding service, ArcGIS Routing service, ArcGIS GeoEnrichment service, and ArcGIS Elevation service. An ArcGIS Location Platform or ArcGIS Online account is required to use the services. Learn more used in this tutorial, you must implement API key authentication API key authentication is a type of authentication that uses an API key to authenticate requests to ArcGIS services and secure portal items. Learn more or user authentication User authentication is a type of authentication that allows users with an ArcGIS account to sign into an application and allow it to access ArcGIS content, services, and resources on their behalf. The typical authorization protocol used is OAuth2.0. Learn more using an ArcGIS Location Platform An ArcGIS Location Platform account, formerly known as an ArcGIS Developer account, is an identity associated with an ArcGIS Location Platform subscription. Learn more or an ArcGIS Online An ArcGIS Online account, also known as an ArcGIS Organization account, is an identity associated with an ArcGIS Online subscription. It can be used to access ArcGIS tools and develop applications with ArcGIS location services for an organization. Learn more account.

To complete this tutorial, click on the tab in the switcher below for your authentication type of choice, either API key authentication or User authentication.

Create a new API key access token An access token is an authorization string that provides access to secure ArcGIS content, data, and services. Its capabilities are determined by the privileges it supports. It is obtained by implementing API key authentication, User authentication, or App authentication. Learn more with privileges Privileges are a set of permissions assigned to ArcGIS accounts, developer credentials, and applications that grant access to secure resources and functionality in ArcGIS. Learn more to access the secure resources used in this tutorial.

  1. Complete the Create an API key tutorial and create an API key with the following privilege(s) Privileges are a set of permissions assigned to ArcGIS accounts, developer credentials, and applications that grant access to secure resources and functionality in ArcGIS. Learn more :

    • Privileges
      • Location services > Basemaps
      • Location services > Routing
  2. Copy and paste the API key access token into a safe location. It will be used in a later step.

Develop or Download

You have two options for completing this tutorial:

  1. Option 1: Develop the code or
  2. Option 2: Download the completed solution

Option 1: Develop the code

To start the tutorial, complete the Display a map tutorial. This creates a map to display the Santa Monica Mountains in California using the topographic basemap from the ArcGIS Basemap Styles service The ArcGIS Basemap Styles service, also referred to as the Basemap Styles service, is a location service that provides basemap styles and data for the world. It returns styles as Mapbox styles and web maps, and data as vector tiles and/or map tiles. It supports all of the styles in the ArcGIS Basemap style and Open Basemap style family. An ArcGIS Location Platform or ArcGIS Online account is required to use the service. Learn more .

Continue with the following instructions to find a route and directions with the ArcGIS Routing service A routing service is a service that uses network analysis and streets data to calculate the most effective path and turn-by-turn directions on a street network, optimize fleet routing and deliveries, find the closest facilities, calculate service areas, and more. It is hosted by Esri as the ArcGIS Routing service and can also be hosted in ArcGIS Enterprise. Learn more . First, you need to set the develop credentials in your app so that your app users can access the ArcGIS Routing service A routing service is a service that uses network analysis and streets data to calculate the most effective path and turn-by-turn directions on a street network, optimize fleet routing and deliveries, find the closest facilities, calculate service areas, and more. It is hosted by Esri as the ArcGIS Routing service and can also be hosted in ArcGIS Enterprise. Learn more .

Set developer credentials

If you implemented API key authentication API key authentication is a type of authentication that uses an API key to authenticate requests to ArcGIS services and secure portal items. Learn more in the Display a map tutorial, the API key access token will only have the Basemaps privilege. The Find a route and directions tutorial requires the Routing privilege to find a route using the RouteTask. To create an API Key access token that has the Basemaps and Routing privileges, see the Set up authentication step and then follow the instructions below.

Pass your API Key access token to the ArcGISEnvironment.

  1. In the Project Navigator, click MainApp.swift.

  2. Set the ArcGISEnvironment.apiKey property with your API key access token.

    MainApp.swift
    ArcGISEnvironment.apiKey = APIKey("<#YOUR-ACCESS-TOKEN#>")

Best Practice: The access token is stored directly in the code as a convenience for this tutorial. Do not store credentials directly in source code in a production environment.

Update the map

A navigation basemap layer A basemap layer is the layer in a map or scene that displays basemap data. The data source for a basemap layer is typically a basemap service. Learn more is typically used in routing applications. Update the basemap to use the .arcGISNavigation basemap style, and change the position of the map to center on Los Angeles.

  1. Update the Basemap style property from .arcGISTopographic to .arcGISNavigation and update the latitude and longitude coordinates to center on Los Angeles.

    ContentView.swift
    struct ContentView: View {
    @State var map = {
    let map = Map(basemapStyle: .arcGISNavigation)
    map.initialViewpoint = Viewpoint(latitude: 34.05293, longitude: -118.24368, scale: 2e5)
    return map
    }()
  2. Create a private class named Model of type ObservableObject and add a @StateObject variable of the Model to the ContentView. See the programming patterns page for more information on how to manage states.

    ContentView.swift
    import SwiftUI
    import ArcGIS
    class Model: ObservableObject {
    }
    struct ContentView: View {
    @StateObject private var model = Model()
    @State var map = {
    let map = Map(basemapStyle: .arcGISNavigation)
    map.initialViewpoint = Viewpoint(latitude: 34.05293, longitude: -118.24368, scale: 2e5)
    return map
    }()
    }

Add graphics to the map view

A graphics overlay A graphics overlay is a client-side, temporary container of graphics to display on a map view or scene view. Learn more is a container for graphics A graphic is a visual element composed of a geometry, symbol, and attributes that is displayed on a map or scene. Learn more . Graphics are added as a visual means to display the search result on the map A map is a collection of layers that are displayed in 2D. It is typically composed of a basemap layer and data layers. Learn more .

  1. In the Model class, create a GraphicsOverlay named graphicsOverlay. In the ContentView, add the graphics overlay A graphics overlay is a client-side, temporary container of graphics to display on a map view or scene view. Learn more to the map view.

    ContentView.swift
    import SwiftUI
    import ArcGIS
    class Model: ObservableObject {
    let graphicsOverlay = GraphicsOverlay()
    }
    struct ContentView: View {
    @StateObject private var model = Model()
    @State var map = {
    let map = Map(basemapStyle: .arcGISNavigation)
    map.initialViewpoint = Viewpoint(latitude: 34.05293, longitude: -118.24368, scale: 2e5)
    return map
    }()
    var body: some View {
    MapView(map: map, graphicsOverlays: [model.graphicsOverlay])
    }
    }
  2. Create a private Graphic property named startGraphic to the Model. Symbolize the graphic with a white circle and black outline. This graphic will be used to display the route’s start location.

    ContentView.swift
    class Model: ObservableObject {
    let graphicsOverlay = GraphicsOverlay()
    let startGraphic: Graphic = {
    let symbol = SimpleMarkerSymbol(style: .circle, color: .white, size: 8)
    symbol.outline = SimpleLineSymbol(style: .solid, color: .black, width: 1)
    let graphic = Graphic(symbol: symbol)
    return graphic
    }()
    }
  3. Create a private Graphic property named endGraphic. Symbolize the graphic with a black circle. This graphic will be used to display the route’s end location.

    ContentView.swift
    class Model: ObservableObject {
    let graphicsOverlay = GraphicsOverlay()
    let startGraphic: Graphic = {
    let symbol = SimpleMarkerSymbol(style: .circle, color: .white, size: 8)
    symbol.outline = SimpleLineSymbol(style: .solid, color: .black, width: 1)
    let graphic = Graphic(symbol: symbol)
    return graphic
    }()
    let endGraphic: Graphic = {
    let symbol = SimpleMarkerSymbol(style: .circle, color: .black, size: 9)
    let graphic = Graphic(symbol: symbol)
    return graphic
    }()
    }
  4. Create a private Graphic property named routeGraphic. Symbolize the graphic with a blue line. This graphic will be used to display the route line A polyline is a type of geometry containing ordered point coordinates and a spatial reference. Learn more .

    ContentView.swift
    let endGraphic: Graphic = {
    let symbol = SimpleMarkerSymbol(style: .circle, color: .black, size: 9)
    let graphic = Graphic(symbol: symbol)
    return graphic
    }()
    let routeGraphic: Graphic = {
    let symbol = SimpleLineSymbol(style: .solid, color: .blue, width: 3)
    let graphic = Graphic(symbol: symbol)
    return graphic
    }()
  5. Create an init() method in the Model that adds startGraphic, endGraphic, and routeGraphic to the graphics overlay. This method will be called when Model is initialized.

    ContentView.swift
    let routeGraphic: Graphic = {
    let symbol = SimpleLineSymbol(style: .solid, color: .blue, width: 3)
    let graphic = Graphic(symbol: symbol)
    return graphic
    }()
    init() {
    graphicsOverlay.addGraphics([routeGraphic, startGraphic, endGraphic])
    }

Create a route task and route parameters

A task makes a request to a service A service, also known as an ArcGIS service, is software that supports an ArcGIS REST API and provides geospatial functionality or data. A service can be hosted by Esri or in ArcGIS Enterprise. Learn more and returns the results. Use the RouteTask class to access a routing service A routing service is a service that uses network analysis and streets data to calculate the most effective path and turn-by-turn directions on a street network, optimize fleet routing and deliveries, find the closest facilities, calculate service areas, and more. It is hosted by Esri as the ArcGIS Routing service and can also be hosted in ArcGIS Enterprise. Learn more .

  1. Continuing in the Model, create a private RouteTask property named routeTask with the routing service.

    ContentView.swift
    init() {
    graphicsOverlay.addGraphics([routeGraphic, startGraphic, endGraphic])
    }
    private let routeTask = RouteTask(
    url: URL(string: "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World")!
    )
  2. Create a variable named directions defined as an array of DirectionManeuver objects. This will contain the step by step directions from the start to the end point.

    ContentView.swift
    private let routeTask = RouteTask(
    url: URL(string: "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World")!
    )
    var directions: [DirectionManeuver] = []
  3. Define a private, asynchronous function named solveRoute(start:end:) that takes a start and end Point. This method will be called when both the start and end points have been placed on the map.

    ContentView.swift
    private let routeTask = RouteTask(
    url: URL(string: "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World")!
    )
    var directions: [DirectionManeuver] = []
    func solveRoute(from start: Point, to end: Point) async throws {
    }
  4. Create default RouteParameters from the routeTask named routeParameters. Configure the parameters by setting two stops (the start and end points) and specify that directions are returned.

    ContentView.swift
    func solveRoute(from start: Point, to end: Point) async throws {
    let routeParameters = try await routeTask.makeDefaultParameters()
    routeParameters.returnsDirections = true
    routeParameters.setStops([Stop(point: start), Stop(point: end)])
    }
  5. Call the solveRoute(using:) function on the routeTask and pass in the routeParameters. To display the solved route, get the first route from the RouteResult and assign its geometry to routeGraphic. To display the directions, assign the directionManeuvers value from the first route to the directions variable.

    ContentView.swift
    func solveRoute(from start: Point, to end: Point) async throws {
    let routeParameters = try await routeTask.makeDefaultParameters()
    routeParameters.returnsDirections = true
    routeParameters.setStops([Stop(point: start), Stop(point: end)])
    let routeResult = try await routeTask.solveRoute(using: routeParameters)
    if let firstRoute = routeResult.routes.first {
    routeGraphic.geometry = firstRoute.geometry
    directions = firstRoute.directionManeuvers
    }
    }

Handle map view touch events

The app will use locations derived from a user tapping the map view A map view is a user interface that displays map layers and graphics in 2D. It controls the area (extent) of the map that is visible and supports user interactions such as pan and zoom. Learn more to generate the stops A stop is a single point along a route: it can be the origin, an intermediate stop, or destination. Learn more on a route A route is a polyline that defines the best path between two or more points in a street network. Learn more . Configure the view to handle touch events from the map view. The locations derived from a user tapping the map view will be used to generate routes in a later step.

  1. In the ContentView struct, create two @State private variables of type Point named startPoint and endPoint. These will contain the start and end locations of the route.

    ContentView.swift
    struct ContentView: View {
    @StateObject private var model = Model()
    @State private var startPoint: Point?
    @State private var endPoint: Point?
    @State var map = {
    let map = Map(basemapStyle: .arcGISNavigation)
    map.initialViewpoint = Viewpoint(latitude: 34.05293, longitude: -118.24368, scale: 2e5)
    return map
    }()
    var body: some View {
    MapView(map: map, graphicsOverlays: [model.graphicsOverlay])
    }
    }
  2. Add the onSingleTapGesture method to the map view. If it is the user’s first tap, set the startPoint to the current mapPoint. Otherwise, set the endPoint to the current mapPoint. Assign the geometries for startGraphic and endGraphic accordingly.

    ContentView.swift
    var body: some View {
    MapView(map: map, graphicsOverlays: [model.graphicsOverlay])
    .onSingleTapGesture { _, mapPoint in
    if startPoint == nil {
    startPoint = mapPoint
    model.startGraphic.geometry = startPoint
    } else {
    endPoint = mapPoint
    model.endGraphic.geometry = endPoint
    }
    }
    }
  3. Add a .task modifier to the map view with endPoint as an identifier. This task is called if the value of endPoint changes. Ensure that the start and end points are not nil and pass them into the model’s solveRoute(start:end:) method. This attempts to solve the route using the start and end points.

    ContentView.swift
    var body: some View {
    MapView(map: map, graphicsOverlays: [model.graphicsOverlay])
    .onSingleTapGesture { _, mapPoint in
    if startPoint == nil {
    startPoint = mapPoint
    model.startGraphic.geometry = startPoint
    } else {
    endPoint = mapPoint
    model.endGraphic.geometry = endPoint
    }
    }
    .task(id: endPoint) {
    guard let startPoint = startPoint, let endPoint = endPoint else { return }
    do {
    try await model.solveRoute(from: startPoint, to: endPoint)
    } catch {
    print(error)
    }
    }
    }

Add a UI to display driving directions

To display the turn-by-turn directions from the route, some UI element is required.

  1. In the ContentView struct, add a Bool variable named isShowingDirections to indicate if the directions are shown or not. Set its initial value to false.

    ContentView.swift
    struct ContentView: View {
    @StateObject private var model = Model()
    @State private var isShowingDirections = false
    @State private var startPoint: Point?
    @State private var endPoint: Point?
    @State var map = {
    let map = Map(basemapStyle: .arcGISNavigation)
    map.initialViewpoint = Viewpoint(latitude: 34.05293, longitude: -118.24368, scale: 2e5)
    return map
    }()
  2. Add a .toolbar and ToolbarItemGroup to the bottom of the map view.

    ContentView.swift
    var body: some View {
    MapView(map: map, graphicsOverlays: [model.graphicsOverlay])
    .onSingleTapGesture { _, mapPoint in
    if startPoint == nil {
    startPoint = mapPoint
    model.startGraphic.geometry = startPoint
    } else {
    endPoint = mapPoint
    model.endGraphic.geometry = endPoint
    }
    }
    .task(id: endPoint) {
    guard let startPoint = startPoint, let endPoint = endPoint else { return }
    do {
    try await model.solveRoute(from: startPoint, to: endPoint)
    } catch {
    print(error)
    }
    }
    .toolbar {
    ToolbarItemGroup(placement: .bottomBar) {
    }
    }
    }
  3. Add a Button, labeled “Show directions”, to the toolbar. This button indicates that the user wants to show the directions so toggle the isShowingDirections value to true.

    ContentView.swift
    .toolbar {
    ToolbarItemGroup(placement: .bottomBar) {
    Button("Show directions") {
    isShowingDirections = true
    }
    }
    }
  4. Add a .popover with a NavigationView to the toolbar. Set the popover’s isPresented parameter to isShowingDirections. The popover will display according to the isShowingDirections value. Customize the navigation view.

    ContentView.swift
    .toolbar {
    ToolbarItemGroup(placement: .bottomBar) {
    Button("Show directions") {
    isShowingDirections = true
    }
    .popover(isPresented: $isShowingDirections) {
    NavigationView {
    }
    .navigationViewStyle(.stack)
    .frame(idealWidth: 320, idealHeight: 428)
    }
    }
    }
  5. Within the NavigationView content, create a List with directions which contains an array of DirectionManeuver objects. Configure the navigation view with a title, display mode, and “Done” button. When the button is tapped, isShowingDirections is set to false which closes the popover.

    ContentView.swift
    .popover(isPresented: $isShowingDirections) {
    NavigationView {
    List(model.directions, id: \.text) { directionManeuver in
    Text(directionManeuver.text)
    }
    .navigationTitle("Directions")
    .navigationBarTitleDisplayMode(.inline)
    .toolbar {
    ToolbarItem(placement: .confirmationAction) {
    Button("Done") {
    isShowingDirections = false
    }
    }
    }
    }
    .navigationViewStyle(.stack)
    .frame(idealWidth: 320, idealHeight: 428)
    }

Run the solution

Press Command + R to run the app.

The map should support two taps to create an origin and destination point and then use the ArcGIS Routing service A routing service is a service that uses network analysis and streets data to calculate the most effective path and turn-by-turn directions on a street network, optimize fleet routing and deliveries, find the closest facilities, calculate service areas, and more. It is hosted by Esri as the ArcGIS Routing service and can also be hosted in ArcGIS Enterprise. Learn more to display the resulting route.

Alternatively, you can download the tutorial solution, as follows.

Option 2: Download the solution

  1. Click the Download solution link under Solution and unzip the file to a location on your machine.

  2. Open the .xcodeproj file in Xcode.

Since the downloaded solution does not contain authentication credentials, you must add the developer credentials that you created in the Set up authentication section.

Set developer credentials in the solution

To allow your app users to access ArcGIS location services ArcGIS Location Services, also referred to as Location Services, are services hosted by Esri that provide geospatial functionality for developing mapping applications. They include the ArcGIS Basemap Styles service, ArcGIS Static Basemap Tiles service, ArcGIS Places service, ArcGIS Geocoding service, ArcGIS Routing service, ArcGIS GeoEnrichment service, and ArcGIS Elevation service. An ArcGIS Location Platform or ArcGIS Online account is required to use the services. Learn more , use the developer credentials that you created in the Set up authentication step to authenticate requests for resources.

Pass your API Key access token to the ArcGISEnvironment.

  1. In the Project Navigator, click MainApp.swift.

  2. Set the AuthenticationMode to .apiKey.

    MainApp.swift
    // Change the `AuthenticationMode` to `.apiKey` if your application uses API key authentication.
    private var authenticationMode: AuthenticationMode { .apiKey }
  3. Set the apiKey property with your API key access token.

    MainApp.swift
    31 collapsed lines
    // Copyright 2022 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 SwiftUI
    import ArcGIS
    import ArcGISToolkit
    @main
    struct MainApp: App {
    // The authentication mode.
    private enum AuthenticationMode {
    case apiKey
    case user
    }
    // Change the `AuthenticationMode` to `.apiKey` if your application uses API key authentication.
    private var authenticationMode: AuthenticationMode { .apiKey }
    // Please enter an API key access token if your application uses API key authentication.
    private let apiKey = APIKey("<#YOUR-ACCESS-TOKEN#>")
    43 collapsed lines
    // Setup an `Authenticator` with OAuth configuration if your application uses OAuth credentials.
    @ObservedObject var authenticator = Authenticator(
    oAuthUserConfigurations: [
    OAuthUserConfiguration(
    // Please enter OAuth credentials for user authentication.
    portalURL: URL(string: "<#YOUR-PORTAL-URL#>")!,
    clientID: "<#YOUR-CLIENT-ID#>",
    redirectURL: URL(string: "<#YOUR-REDIRECT-URL#>")!
    )
    ]
    )
    func setAuthentication() {
    switch authenticationMode {
    case .apiKey:
    ArcGISEnvironment.apiKey = apiKey
    case .user:
    ArcGISEnvironment.authenticationManager.arcGISAuthenticationChallengeHandler = authenticator
    }
    }
    init() {
    setAuthentication()
    }
    var body: some SwiftUI.Scene {
    WindowGroup {
    ContentView()
    .authenticator(authenticator)
    .ignoresSafeArea()
    }
    }
    }

Best Practice: The access token is stored directly in the code as a convenience for this tutorial. Do not store credentials directly in source code in a production environment.

Run the solution

Press Command + R to run the app.

The map should support two taps to create an origin and destination point and then use the ArcGIS Routing service A routing service is a service that uses network analysis and streets data to calculate the most effective path and turn-by-turn directions on a street network, optimize fleet routing and deliveries, find the closest facilities, calculate service areas, and more. It is hosted by Esri as the ArcGIS Routing service and can also be hosted in ArcGIS Enterprise. Learn more to display the resulting route.

What’s next?

Learn how to use additional API features, ArcGIS location services, and ArcGIS tools in these tutorials: