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.returnsDirectionstotrue. - Create a
Stopfor each graphic in the stops graphics overlay. Add that stop to a list, then callRouteParameters.setStops(_:). - Create a
PolygonBarrierfor 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.findsBestSequencetotrueto find the most optimal route. - If the user has a definite start point, set
RouteParameters.preservesFirstStoptotrue. - If the user has a definite final destination, set
RouteParameters.preservesLastStoptotrue.
- 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.geometryproperty. - 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 ArcGISimport 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?
/// A Boolean value indicating whether the settings view is showing. @State private var settingsAreVisible = false
/// A Boolean value indicating whether the directions list is showing. @State private var routeIsShowing = false
/// The error shown in the error alert. @State private var error: (any 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) { Spacer() Button("Directions", systemImage: "arrow.triangle.turn.up.right.diamond") { routeIsShowing = true } .labelsHidden() .popover(isPresented: $routeIsShowing) { routeSheet .presentationDetents([.fraction(0.35)]) .frame(idealWidth: 400, idealHeight: 400) } .disabled(model.route == nil) .task(id: directionGeometry) { guard let directionGeometry else { return } model.directionGraphic.geometry = directionGeometry await mapViewProxy.setViewpointGeometry(directionGeometry, padding: 100) } Spacer() Button("Get 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() Button("Settings", systemImage: "gear") { settingsAreVisible = true } .labelsHidden() .popover(isPresented: $settingsAreVisible) { settings .frame(idealWidth: 400, idealHeight: 500) .presentationCompactAdaptation(.popover) }
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) }
@ViewBuilder var routeSheet: some View { NavigationStack { List(model.route?.directionManeuvers ?? [], id: \.text) { direction in Button(direction.text) { directionGeometry = direction.geometry } } .navigationTitle("Route Directions") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { routeIsShowing = false } } } } }
@ViewBuilder var settings: some View { NavigationStack { Form { Section("Features") { Picker("Features", selection: $featuresSelection) { Text("Stops").tag(RouteFeatures.stops) Text("Barriers").tag(RouteFeatures.barriers) } .pickerStyle(.segmented) } RouteParametersSettings(routeParameters: model.routeParameters) } .navigationTitle("Settings") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { settingsAreVisible = false } } } } }}
extension FindRouteAroundBarriersView { /// A list of settings for modifying route parameters. struct RouteParametersSettings: View { /// The route parameters to modify. let routeParameters: RouteParameters
/// A Boolean value indicating whether routing will find the best sequence. @State private var routingFindsBestSequence = true /// A Boolean value indicating whether routing will preserve the first stop. @State private var routePreservesFirstStop = true /// A Boolean value indicating whether routing will preserve the last stop. @State private var routePreservesLastStop = true
var body: some View { Section { Toggle("Find Best Sequence", isOn: $routingFindsBestSequence) .onChange(of: routingFindsBestSequence) { routeParameters.findsBestSequence = routingFindsBestSequence } } Section("Preserve Stops") { Toggle("Preserve First Stop", isOn: $routePreservesFirstStop) .onChange(of: routePreservesFirstStop) { routeParameters.preservesFirstStop = routePreservesFirstStop } Toggle("Preserve Last Stop", isOn: $routePreservesLastStop) .onChange(of: routePreservesLastStop) { routeParameters.preservesLastStop = routePreservesLastStop } } .disabled(!routingFindsBestSequence) .onAppear { routingFindsBestSequence = routeParameters.findsBestSequence routePreservesFirstStop = routeParameters.preservesFirstStop routePreservesLastStop = routeParameters.preservesLastStop } } }}
#Preview { NavigationStack { FindRouteAroundBarriersView() }}// 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 ArcGISimport Combineimport UIKit
extension FindRouteAroundBarriersView { /// The view model for the sample. @MainActor class Model: ObservableObject { // MARK: Properties
/// A map with a topographic basemap cantered on San Diego, CA, USA. let map = { let map = Map(basemapStyle: .arcGISTopographic) map.initialViewpoint = Viewpoint( center: Point(x: -13_042_200, y: 3_857_900, spatialReference: .webMercator), scale: 1e5 ) return map }()
/// The graphics overlays for the sample. let graphicsOverlays: [GraphicsOverlay]
/// The graphics overlay for the stop graphics. private let stopGraphicsOverlay = GraphicsOverlay()
/// The graphics overlay for the barrier graphics. private let barrierGraphicsOverlay = GraphicsOverlay()
/// The graphics overlay for the route graphics. private let routeGraphicsOverlay = GraphicsOverlay()
/// The blue marker symbol for the stop graphics. private let stopSymbol = { let markerImage = UIImage.blueMarker let markerSymbol = PictureMarkerSymbol(image: markerImage) markerSymbol.offsetY = markerImage.size.height / 2 return markerSymbol }()
/// The yellow line graphic for the route. private let routeGraphic = Graphic( symbol: SimpleLineSymbol(style: .solid, color: .yellow, width: 5) )
/// The dashed orange line graphic for the direction route. let directionGraphic = Graphic( symbol: SimpleLineSymbol(style: .dashDot, color: .orange, width: 5) )
/// The route task for routing. let routeTask = RouteTask(url: .sanDiegoNetworkAnalysis)
/// The route parameters for routing with the route task. var routeParameters = RouteParameters()
/// The resulting route from a routing operation with the route task. private(set) var route: Route?
/// The text with the time and distance of the current route. @Published private(set) var routeInfoText = ""
/// The count of stops currently on the map. @Published private(set) var stopsCount = 0
/// The count of barriers currently on the map. @Published private(set) var barriersCount = 0
init() { routeGraphicsOverlay.addGraphics([routeGraphic, directionGraphic]) graphicsOverlays = [routeGraphicsOverlay, barrierGraphicsOverlay, stopGraphicsOverlay] updateRouteInfoText() }
// MARK: Methods
/// Adds a stop graphic to the map. /// - Parameter point: The point to add the stop graphic at. func addStopGraphic(at point: Point) { // Create a text symbol with the next index. let textSymbol = TextSymbol( text: "\(stopsCount + 1)", color: .white, size: 20, horizontalAlignment: .center, verticalAlignment: .middle ) textSymbol.offsetY = stopSymbol.offsetY
// Create a graphic with the marker symbol and text symbol. let compositeSymbol = CompositeSymbol(symbols: [stopSymbol, textSymbol]) let stopGraphic = Graphic(geometry: point, symbol: compositeSymbol)
// Add the new graphic to the stop graphics overlay. stopGraphicsOverlay.addGraphic(stopGraphic) stopsCount += 1 }
/// Adds a barrier graphic to the map. /// - Parameter point: The point to add the barrier graphic at. func addBarrierGraphic(at point: Point) { // Buffer the point and create the barrier symbol. let bufferedGeometry = GeometryEngine.buffer(around: point, distance: 500) let barrierSymbol = SimpleFillSymbol(style: .diagonalCross, color: .red)
// Create a graphic from the symbol and buffer and add it to the graphics overlay. let barrierGraphic = Graphic(geometry: bufferedGeometry, symbol: barrierSymbol) barrierGraphicsOverlay.addGraphic(barrierGraphic) barriersCount += 1 }
/// Resets all the features on the map associated with a given feature type. /// - Parameter features: The features to remove from the map. func reset(features: RouteFeatures) { if features == .stops { // Reset the stops. stopGraphicsOverlay.removeAllGraphics() stopsCount = 0
// Reset the route. route = nil routeGraphic.geometry = nil directionGraphic.geometry = nil updateRouteInfoText() } else { barrierGraphicsOverlay.removeAllGraphics() barriersCount = 0 } }
/// Routes using the route parameters and the current stops and barriers on the map. func route() async throws { // Update the route parameters' stops using the stop graphics. routeParameters.setStops( stopGraphicsOverlay.graphics .compactMap { $0.geometry as? Point } .map(Stop.init(point:)) )
// Update the route parameters' barriers using the barrier graphics. routeParameters.setPolygonBarriers( barrierGraphicsOverlay.graphics .compactMap { $0.geometry as? ArcGIS.Polygon } .map(PolygonBarrier.init(polygon:)) )
// Get the route from the route task using the updated route parameters. let routeResult = try await routeTask.solveRoute(using: routeParameters) guard let route = routeResult.routes.first else { return }
// Update the route's associated properties. self.route = route directionGraphic.geometry = nil routeGraphic.geometry = route.geometry updateRouteInfoText() }
/// Updates the route info text using the current route. private func updateRouteInfoText() { guard let route else { routeInfoText = "Tap to add a stop or barrier." return }
// Format the route's time. let dateInterval = DateInterval(start: .now, duration: route.totalTime) let dateRange = dateInterval.start..<dateInterval.end let timeText = dateRange.formatted( .components(style: .abbreviated, fields: [.day, .hour, .minute]) )
// Format the route's distance. let distanceText = route.totalLength.formatted()
routeInfoText = "\(timeText) (\(distanceText))" } }
/// An enumeration representing the different groups of route features in this sample. enum RouteFeatures { /// The stops along the route. case stops
/// The areas that can't be crossed by the route. case barriers }}
private extension URL { /// The URL to a network analysis server of San Diego, CA, USA on ArcGIS Online. static var sanDiegoNetworkAnalysis: URL { URL( string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route" )! }}