Find route around barriers

View on GitHub

Find a route that reaches all stops without crossing any barriers.

Image of find route around barriers Image of find route around barriers

Use case

You can define barriers to avoid unsafe areas, for example flooded roads, when planning the most efficient route to evacuate a hurricane zone. When solving a route, barriers allow you to define portions of the road network that cannot be traversed. You could also use this functionality to plan routes when you know an area will be inaccessible due to a community activity like an organized race or a market night.

In some situations, it is further beneficial to find the most efficient route that reaches all stops, reordering them to reduce travel time. For example, a delivery service may target a number of drop-off addresses, specifically looking to avoid congested areas or closed roads, arranging the stops in the most time-effective order.

How to use the sample

Select "Stops" and tap on the map to add stops to the route. Select "Barriers" and tap on the map to add areas that can't be crossed by the route. Tap "Route" to find the route and display it. Tap the settings button to toggle preferences like find the best sequence or preserve the first or last stop. Additionally, tap the directions button to view a list of the directions.

How it works

  1. Create the route task by calling RouteTask.init(url:) with the URL to a Network Analysis route service.
  2. Get the default route parameters for the service by calling RouteTask.makeDefaultParameters().
  3. When the user adds a stop, add it to the route parameters.
    1. Normalize the geometry; otherwise the route job would fail if the user included any stops over the 180th degree meridian.
    2. Create a composite symbol for the stop. This sample uses a blue marker and a text symbol.
    3. Create the graphic from the geometry and the symbol.
    4. Add the graphic to the stops graphics overlay.
  4. When the user adds a barrier, create a polygon barrier and add it to the route parameters.
    1. Normalize the geometry (see 3i above).
    2. Buffer the geometry to create a larger barrier from the tapped point by calling GeometryEngine.buffer(around:distance:).
    3. Create the graphic from the geometry and the symbol.
    4. Add the graphic to the barriers overlay.
  5. When ready to find the route, configure the route parameters.
    1. Set RouteParameters.returnsDirections to true.
    2. Create a Stop for each graphic in the stops graphics overlay. Add that stop to a list, then call RouteParameters.setStops(_:).
    3. Create a PolygonBarrier for each graphic in the barriers graphics overlay. Add that barrier to a list, then call RouteParameters.setPolygonBarriers(_:).
    4. If the user will accept routes with the stops in any order, set RouteParameters.findsBestSequence to true to find the most optimal route.
    5. If the user has a definite start point, set RouteParameters.preservesFirstStop to true.
    6. If the user has a definite final destination, set RouteParameters.preservesLastStop to true.
  6. Calculate and display the route.
    1. Call RouteTask.solveRoute(using:) to get a RouteResult.
    2. Get the first returned route by calling RouteResult.routes.first.
    3. Get the geometry from the route as a polyline by accessing the Route.geometry property.
    4. Create a graphic from the polyline and a simple line symbol.
    5. Display the steps on the route, available from Route.directionManeuvers.

Relevant API

  • DirectionManeuver
  • PolygonBarrier
  • Route
  • Route.directionManeuvers
  • Route.geometry
  • RouteParameters.clearPolygonBarriers
  • RouteParameters.findsBestSequence
  • RouteParameters.preservesFirstStop
  • RouteParameters.preservesLastStop
  • RouteParameters.returnsDirections
  • RouteParameters.setPolygonBarriers
  • RouteResult
  • RouteResult.routes
  • RouteTask
  • Stop

About the data

This sample uses an Esri-hosted sample street network for San Diego.

Tags

barriers, best sequence, directions, maneuver, network analysis, routing, sequence, stop order, stops

Sample Code

FindRouteAroundBarriersView.swiftFindRouteAroundBarriersView.swiftFindRouteAroundBarriersView.Model.swiftFindRouteAroundBarriersView.Views.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
// 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 SwiftUI

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

    /// The route features to be added or removed from the map.
    @State private var featuresSelection: RouteFeatures = .stops

    /// A Boolean value indicating whether a routing operation is in progress.
    @State private var routingIsInProgress = false

    /// The geometry of a direction maneuver to set the viewpoint to.
    @State private var directionGeometry: Geometry?

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

    var body: some View {
        MapViewReader { mapViewProxy in
            MapView(map: model.map, graphicsOverlays: model.graphicsOverlays)
                .onSingleTapGesture { _, mapPoint in
                    // Normalize the map point.
                    guard let normalizedPoint = GeometryEngine.normalizeCentralMeridian(
                        of: mapPoint
                    ) as? Point else { return }

                    // Add a stop or barrier depending on the current features selection.
                    if featuresSelection == .stops {
                        model.addStopGraphic(at: normalizedPoint)
                    } else {
                        model.addBarrierGraphic(at: normalizedPoint)
                    }
                }
                .overlay(alignment: .top) {
                    Text(model.routeInfoText)
                        .frame(maxWidth: .infinity, alignment: .center)
                        .padding(8)
                        .background(.thinMaterial, ignoresSafeAreaEdges: .horizontal)
                }
                .overlay(alignment: .center) {
                    if routingIsInProgress {
                        ProgressView("Routing...")
                            .padding()
                            .background(.ultraThickMaterial)
                            .cornerRadius(10)
                            .shadow(radius: 50)
                    }
                }
                .toolbar {
                    ToolbarItemGroup(placement: .bottomBar) {
                        Button("Route") {
                            routingIsInProgress = true
                        }
                        .disabled(model.stopsCount < 2)
                        .task(id: routingIsInProgress) {
                            guard routingIsInProgress else { return }

                            do {
                                // Route when the button is pressed
                                try await model.route()

                                // Update the viewpoint to the geometry of the new route.
                                guard let geometry = model.route?.geometry else { return }
                                await mapViewProxy.setViewpointGeometry(geometry, padding: 50)
                            } catch {
                                self.error = error
                            }

                            routingIsInProgress = false
                        }
                        Spacer()

                        SheetButton(title: "Directions") {
                            List {
                                ForEach(
                                    Array((model.route?.directionManeuvers ?? []).enumerated()),
                                    id: \.offset
                                ) { (_, direction) in
                                    Button {
                                        directionGeometry = direction.geometry
                                    } label: {
                                        Text(direction.text)
                                    }
                                }
                            }
                        } label: {
                            Image(systemName: "arrow.triangle.turn.up.right.diamond")
                        }
                        .disabled(model.route == nil)
                        .task(id: directionGeometry) {
                            guard let directionGeometry else { return }
                            model.directionGraphic.geometry = directionGeometry
                            await mapViewProxy.setViewpointGeometry(directionGeometry, padding: 100)
                        }
                        Spacer()

                        Picker("Features", selection: $featuresSelection) {
                            Text("Stops").tag(RouteFeatures.stops)
                            Text("Barriers").tag(RouteFeatures.barriers)
                        }
                        .pickerStyle(.segmented)
                        .labelsHidden()
                        Spacer()

                        SheetButton(title: "Route Settings") {
                            RouteParametersSettings(for: model.routeParameters)
                        } label: {
                            Image(systemName: "gear")
                        }
                        Spacer()

                        Button {
                            model.reset(features: featuresSelection)
                        } label: {
                            Image(systemName: "trash")
                        }
                        .disabled(
                            featuresSelection == .stops ? model.stopsCount == 0 :
                                model.barriersCount == 0
                        )
                    }
                }
        }
        .task {
            // Load the default route parameters from the route task when the sample loads.
            do {
                model.routeParameters = try await model.routeTask.makeDefaultParameters()
                model.routeParameters.returnsDirections = true
            } catch {
                self.error = error
            }
        }
        .errorAlert(presentingError: $error)
    }
}

#Preview {
    NavigationStack {
        FindRouteAroundBarriersView()
    }
}

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