Learn how to find a route and directions with the route service.
Routing is the process of finding the path from an origin to a destination in a street network. You can use the Routing service to find routes, 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:
-
You need an ArcGIS Location Platform or ArcGIS Online account.
-
Your system meets the system requirements.
Steps
Get an access token
You need an access token to use the location services used in this tutorial.
-
Go to the Create an API key tutorial to obtain an access token.
-
Ensure that the following privileges are enabled: Location services > Basemaps > Basemap styles service and Location services > Routing.
-
Copy the access token as it will be used in the next step.
To learn more about other ways to get an access token, go to Types of authentication.
Open the Xcode project
-
To start the tutorial, complete the Display a map tutorial or download and unzip the solution.
-
Open the
.xcodeproj
file in Xcode. -
In Xcode, in the Project Navigator, click MainApp.swift.
-
In the Editor, set the
ArcGISEnvironment.apiKey
property on theArcGIS
with your copied access token.Environment MainApp.swiftUse dark colors for code blocks init() { ArcGISEnvironment.apiKey = APIKey("<#YOUR-ACCESS-TOKEN#>") }
Update the map
A navigation basemap layer is typically used in routing applications. Update the basemap to use the .arc
basemap style, and change the position of the map to center on Los Angeles.
-
Update the
Basemap
style property from.arc
toGIS Topographic .arc
and update the latitude and longitude coordinates to center on Los Angeles.GIS Navigation ContentView.swiftUse dark colors for code blocks 69 70 71 72 75 76 77Change line Change line struct ContentView: View { @State var map = { let map = Map(basemapStyle: .arcGISNavigation) map.initialViewpoint = Viewpoint(latitude: 34.05293, longitude: -118.24368, scale: 2e5) return map }()
-
Create a private class named
Model
of typeObservable
and add aObject @
variable of theState Object Model
to theContent
. See the programming patterns page for more information on how to manage states.View ContentView.swiftUse dark colors for code blocks 16 17 18 19 23 24 25 27 28 29 30 31 32 33 34 35 36Add line. Add line. Add line. Add line. 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 is a container for graphics. Graphics are added as a visual means to display the search result on the map.
-
In the
Model
class, create aGraphicsOverlay
namedgraphics
. In theOverlay Content
, add the graphics overlay to the map view.View A graphics overlay is a container for graphics. It is used with a map view to display graphics on a map. You can add more than one graphics overlay to a map view. Graphics overlays are displayed on top of all the other layers.
ContentView.swiftUse dark colors for code blocks 16 17 18 19 20 21 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 41 42 43 44Add line. Change line 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]) } }
-
Create a private
Graphic
property namedstart
to theGraphic Model
. Symbolize the graphic with a white circle and black outline. This graphic will be used to display the route's start location.An
SimpleMarkerSymbol
is used to display a location on the map view.ContentView.swiftUse dark colors for code blocks 20 21 22 23 30 31Add line. Add line. Add line. Add line. Add line. Add line. 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 }() }
-
Create a private
Graphic
property namedend
. Symbolize the graphic with a black circle. This graphic will be used to display the route's end location.Graphic ContentView.swiftUse dark colors for code blocks 20 21 22 23 24 25 26 27 28 29 30 36 37Add line. Add line. Add line. Add line. Add line. 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 }() }
-
Create a private
Graphic
property namedroute
. Symbolize the graphic with a blue line. This graphic will be used to display the route line.Graphic An
SimpleLineSymbol
is used to display a line on the map view.ContentView.swiftUse dark colors for code blocks 31 32 33 34 35 36Add line. Add line. Add line. Add line. Add line. 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 }()
-
Create an
init()
method in theModel
that addsstart
,Graphic end
, andGraphic route
to the graphics overlay. This method will be called whenGraphic Model
is initialized.Because
start
,Graphic end
, andGraphic route
haven't yet specified aGraphic Geometry
, they will not be visible.ContentView.swiftUse dark colors for code blocks 37 38 39 40 41 42Add line. Add line. Add line. 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 and returns the results. Use the RouteTask
class to access a routing service.
A routing service with global coverage is part of ArcGIS location services. You can also publish custom routing services using ArcGIS Enterprise.
-
Continuing in the
Model
, create a privateRouteTask
property namedroute
with the routing service.Task ContentView.swiftUse dark colors for code blocks 43 44 45 46Add line. Add line. Add line. 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")! )
-
Create a variable named
directions
defined as an array ofDirectionManeuver
objects. This will contain the step by step directions from the start to the end point.ContentView.swiftUse dark colors for code blocks 47 48 49 50 52Add line. private let routeTask = RouteTask( url: URL(string: "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World")! ) var directions: [DirectionManeuver] = []
-
Define a private, asynchronous function named
solve
that takes a start and endRoute(start :end :) Point
. This method will be called when both the start and end points have been placed on the map.ContentView.swiftUse dark colors for code blocks 47 48 49 50 51 52Add line. Add line. Add line. 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 { }
-
Create default
RouteParameters
from theroute
namedTask route
. Configure the parameters by setting two stops (the start and end points) and specify that directions are returned.Parameters ContentView.swiftUse dark colors for code blocks 53 54 58 59Add line. Add line. Add line. 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)]) }
-
Call the
solve
function on theRoute(using :) route
and pass in theTask route
. To display the solved route, get the first route from theParameters RouteResult
and assign itsgeometry
toroute
. To display the directions, assign theGraphic direction
value from the first route to theManeuvers directions
variable.ContentView.swiftUse dark colors for code blocks 53 54 55 56 57 58 64 65Add line. Add line. Add line. Add line. Add line. 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 to generate the stops on a route. 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.
-
In the
Content
struct, create twoView @
private variables of typeState Point
namedstart
andPoint end
. These will contain the start and end locations of the route.Point ContentView.swiftUse dark colors for code blocks 69 70 71 72 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90Add line. Add line. 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]) } }
-
Add the
onSingleTapGesture
method to the map view. If it is the user's first tap, set thestart
to the currentPoint map
. Otherwise, set thePoint end
to the currentPoint map
. Assign the geometries forPoint start
andGraphic end
accordingly.Graphic ContentView.swiftUse dark colors for code blocks 86 87 88 89 99 100Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. 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 } } }
-
Add a
.task
modifier to the map view withend
as an identifier. This task is called if the value ofPoint end
changes. Ensure that the start and end points are not nil and pass them into the model'sPoint solve
method. This attempts to solve the route using the start and end points.Route(start :end :) ContentView.swiftUse dark colors for code blocks 86 87 88 89 90 91 92 93 94 95 96 97 98 99 108 109Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. 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.
-
In the ContentView struct, add a
Bool
variable namedis
to indicate if the directions are shown or not. Set its initial value toShowing Directions false
.ContentView.swiftUse dark colors for code blocks 69 70 71 72 74 75 76 77 78 79 80 81 82 83 84Add line. 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 }()
-
Add a
.toolbar
andToolbar
to the bottom of the map view.Item Group ContentView.swiftUse dark colors for code blocks 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 114 115Add line. Add line. Add line. Add line. Add line. 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) { } } }
-
Add a
Button
, labeled "Show directions", to the toolbar. This button indicates that the user wants to show the directions so toggle theis
value toShowing Directions true
.ContentView.swiftUse dark colors for code blocks 109 110 111 115 116 117Add line. Add line. Add line. .toolbar { ToolbarItemGroup(placement: .bottomBar) { Button("Show directions") { isShowingDirections = true } } }
-
Add a
.popover
with aNavigation
to the toolbar. Set the popover'sView is
parameter toPresented is
. The popover will display according to theShowing Directions is
value. Customize the navigation view.Showing Directions ContentView.swiftUse dark colors for code blocks 109 110 111 112 113 114 115 123 124 125Add line. Add line. Add line. Add line. Add line. Add line. Add line. .toolbar { ToolbarItemGroup(placement: .bottomBar) { Button("Show directions") { isShowingDirections = true } .popover(isPresented: $isShowingDirections) { NavigationView { } .navigationViewStyle(.stack) .frame(idealWidth: 320, idealHeight: 428) } } }
-
Within the
Navigation
content, create aView List
withdirections
which contains an array ofDirectionManeuver
objects. Configure the navigation view with a title, display mode, and "Done" button. When the button is tapped,is
is set toShowing Directions false
which closes the popover.ContentView.swiftUse dark colors for code blocks 116 117 118 131 132 133 134 135Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. .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) }
-
Press Command + R to run the app.
If you are using the Xcode simulator your system must meet these minimum requirements: macOS Monterey 12.5, Xcode 15, iOS 17. If you are using a physical device, then refer to the system requirements.
The map should support two taps to create an origin and destination point and then use the route service to display the resulting route.
What's next?
Learn how to use additional API features, ArcGIS location services, and ArcGIS tools in these tutorials: