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