Route around barriers

View on GitHubSample viewer app

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

Route around barriers Directions for 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

Tap "Add stop" to add stops to the route. Tap "Add barrier" 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 using AGSRouteTask.init(url:) with the URL to a Network Analysis route service.
  2. Get the default route parameters for the service by using AGSRouteTask.defaultRouteParameters(completion:).
  3. When the user adds a stop, add it to the route parameters. i. Normalize the geometry; otherwise the route job would fail if the user included any stops over the 180th degree meridian. ii. Get the name of the stop by counting the existing stops - stopGraphicsOverlay.graphics.index(of:) + 1. iii. Create a composite symbol for the stop. This sample uses a blue marker and a text symbol. iv. Create the graphic from the geometry and the symbol. v. 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. i. Normalize the geometry (see 3i above). ii. Buffer the geometry to create a larger barrier from the tapped point by calling class AGSGeometryEngine.bufferGeometry(geometry:byDistance:). iii. Create the graphic from the geometry and the symbol. iv. Add the graphic to the barriers overlay.
  5. When ready to find the route, configure the route parameters. i. Set the returnStops and returnDirections to true. ii. Create an AGSStop for each graphic in the stops graphics overlay. Add that stop to a list, then call AGSRouteParameters.setStops(_:). iii. Create a AGSPolygonBarrier for each graphic in the barriers graphics overlay. Add that barrier to a list, then call AGSRouteParameters.setPolygonBarriers(_:). iv. If the user will accept routes with the stops in any order, set findBestSequence to true to find the most optimal route. v. If the user has a definite start point, set AGSRouteParameters.preserveFirstStop to true. vi. If the user has a definite final destination, set AGSRouteParameters.preserveLastStop to true.
  6. Calculate and display the route. i. Call AGSRouteTask.solveRoute(with:completion:) to get an AGSRouteResult. ii. Get the first returned route by calling AGSRouteResult.routes.first(). iii. Get the geometry from the route as a polyline by accessing the routeGeometry property. iv. Create a graphic from the polyline and a simple line symbol. v. Display the steps on the route, available from directionManeuvers.

Relevant API

  • AGSDirectionManeuver
  • AGSPolygonBarrier
  • AGSRoute
  • AGSRoute.directionManeuvers
  • AGSRoute.routeGeometry
  • AGSRouteParameters.clearPolygonBarriers
  • AGSRouteParameters.findBestSequence
  • AGSRouteParameters.preserveFirstStop
  • AGSRouteParameters.preserveLastStop
  • AGSRouteParameters.returnDirections
  • AGSRouteParameters.returnStops
  • AGSRouteParameters.setPolygonBarriers
  • AGSRouteResult
  • AGSRouteResult.routes
  • AGSRouteTask
  • AGSStop
  • AGSStop.name

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

DirectionsListViewController.swiftDirectionsListViewController.swiftRouteAroundBarriersViewController.swiftRouteParametersViewController.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
//
// Copyright 2016 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
//
//   http://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 UIKit
import ArcGIS

protocol DirectionsListViewControllerDelegate: AnyObject {
    func directionsListViewController(_ directionsListViewController: DirectionsListViewController, didSelectDirectionManuever directionManeuver: AGSDirectionManeuver)
    func directionsListViewControllerDidDeleteRoute(_ directionsListViewController: DirectionsListViewController)
}

class DirectionsListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet var tableView: UITableView!
    @IBOutlet var milesLabel: UILabel!
    @IBOutlet var minutesLabel: UILabel!

    weak var delegate: DirectionsListViewControllerDelegate?

    var route: AGSRoute! {
        didSet {
            self.tableView?.reloadData()
            self.updateLabels()
        }
    }

    func updateLabels() {
        if self.route != nil {
            let miles = String(format: "%.2f", self.route.totalLength * 0.000621371)
            self.milesLabel.text = "(\(miles) mi)"

            var minutes = Int(self.route.totalTime)
            let hours = minutes / 60
            minutes = minutes % 60
            let hoursString = hours == 0 ? "" : "\(hours) hr "
            let minutesString = minutes == 0 ? "" : "\(minutes) min"
            self.minutesLabel.text = "\(hoursString)\(minutesString)"
        }
    }

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.route?.directionManeuvers.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DirectionCell", for: indexPath)

        cell.textLabel?.text = self.route.directionManeuvers[indexPath.row].directionText

        return cell
    }

    // MARK: - UITableViewDelegate

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let directionManeuver = self.route.directionManeuvers[indexPath.row]
        self.delegate?.directionsListViewController(self, didSelectDirectionManuever: directionManeuver)
    }

    // MARK: - Actions

    @IBAction func deleteRouteAction() {
        self.delegate?.directionsListViewControllerDidDeleteRoute(self)
    }
}

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