Find closest facility to multiple incidents (service)

View on GitHubSample viewer app

Find routes from several locations to the respective closest facility.

Screenshot of Find Closest Facility to Multiple Incidents Service sample

Use case

Quickly and accurately determining the most efficient route between a location and a facility is a frequently encountered task. For example, a city's fire department may need to know which fire stations in the vicinity offer the quickest routes to multiple fires. Solving for the closest fire station to the fire's location using an impedance of "travel time" would provide this information.

How to use the sample

Tap the Solve Routes button to solve and display the route from each incident (fire) to the nearest facility (fire station).

How it works

  1. Create an instance of AGSClosestFacilityTask using a URL to an online service.
  2. Get the default set of closest facility parameters from the task.
  3. Create separate arrays of all facilities and all incidents:
  • Create an instance of AGSFeatureTable with the URL of a feature layer.
  • Query the feature table for all features.
  • Iterate over the found features and add each to the array, instantiating the feature as an AGSFacility or an AGSIncident.
  1. Add the array of all facilities to the task parameters.
  2. Add the array of all incidents to the task parameters.
  3. Get an AGSClosestFacilityResult by solving the task with the provided parameters.
  4. Find the closest facility for each incident by iterating over the array of incidents.
  5. Display the route as an AGSGraphic.

Relevant API

  • AGSClosestFacilityParameters
  • AGSClosestFacilityResult
  • AGSClosestFacilityRoute
  • AGSClosestFacilityTask
  • AGSFacility
  • AGSGraphic
  • AGSGraphicsOverlay
  • AGSIncident

Tags

incident, network analysis, route, search

Sample Code

FindClosestFacilityMultipleIncidentsServiceViewController.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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
//
// Copyright © 2019 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

/// A view controller that manages the interface of the Find Closest Facility to
/// Multiple Incidents (Service) sample.
class FindClosestFacilityMultipleIncidentsServiceViewController: UIViewController {
    /// The map view managed by the view controller.
    @IBOutlet weak var mapView: AGSMapView! {
        didSet {
            mapView.map = makeMap()
            mapView.graphicsOverlays.add(routesOverlay)
        }
    }
    /// The bar button item that initiates the solve route operation.
    @IBOutlet weak var solveRoutesButtonItem: UIBarButtonItem!
    /// The bar button item that removes the solved routes.
    @IBOutlet weak var resetButtonItem: UIBarButtonItem!

    /// The graphics overlay for the routes.
    let routesOverlay = AGSGraphicsOverlay()

    /// The facility features.
    var facilityFeatures = [AGSFeature]()
    /// The incident features.
    var incidentFeatures = [AGSFeature]()
    /// The task used to find the closest facilities.
    let closestFacilityTask: AGSClosestFacilityTask = {
        let url = URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ClosestFacility")!
        return AGSClosestFacilityTask(url: url)
    }()

    /// Creates a feature layer with the facilities. It is configured to render
    /// the facilities using a fire station image.
    ///
    /// - Returns: A new `AGSFeatureLayer` object.
    func makeFacilitiesLayer() -> AGSFeatureLayer {
        let facilitiesTableURL = URL(string: "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/San_Diego_Facilities/FeatureServer/0")!
        let facilitiesTable = AGSServiceFeatureTable(url: facilitiesTableURL)
        let facilitiesLayer = AGSFeatureLayer(featureTable: facilitiesTable)

        let facilityImageURL = URL(string: "https://static.arcgis.com/images/Symbols/SafetyHealth/FireStation.png")!
        let facilitySymbol = AGSPictureMarkerSymbol(url: facilityImageURL)
        facilitySymbol.width = 30
        facilitySymbol.height = 30
        facilitiesLayer.renderer = AGSSimpleRenderer(symbol: facilitySymbol)

        return facilitiesLayer
    }

    /// Creates a feature layer with the incidents. It is configured to render
    /// the incidents using a fire image.
    ///
    /// - Returns: A new `AGSFeatureLayer` object.
    func makeIncidentsLayer() -> AGSFeatureLayer {
        let incidentsTableURL = URL(string: "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/San_Diego_Incidents/FeatureServer/0")!
        let incidentsTable = AGSServiceFeatureTable(url: incidentsTableURL)
        let incidentsLayer = AGSFeatureLayer(featureTable: incidentsTable)

        let incidentsImageURL = URL(string: "https://static.arcgis.com/images/Symbols/SafetyHealth/esriCrimeMarker_56_Gradient.png")!
        let incidentsSymbol = AGSPictureMarkerSymbol(url: incidentsImageURL)
        incidentsSymbol.width = 30
        incidentsSymbol.height = 30
        incidentsLayer.renderer = AGSSimpleRenderer(symbol: incidentsSymbol)

        return incidentsLayer
    }

    /// Creates a map.
    ///
    /// - Returns: A new `AGSMap` object.
    func makeMap() -> AGSMap {
        let map = AGSMap(basemapStyle: .arcGISStreetsRelief)

        let facilitiesLayer = makeFacilitiesLayer()
        let incidentsLayer = makeIncidentsLayer()
        map.operationalLayers.addObjects(from: [facilitiesLayer, incidentsLayer])

        let dispatchGroup = DispatchGroup()
        dispatchGroup.enter()
        queryAllFeatures(from: facilitiesLayer.featureTable!) { [weak self] (result) in
            switch result {
            case .success(let features):
                self?.facilityFeatures = features
            case .failure(let error):
                self?.presentAlert(error: error)
            }
            dispatchGroup.leave()
        }
        dispatchGroup.enter()
        queryAllFeatures(from: incidentsLayer.featureTable!) { [weak self] (result) in
            switch result {
            case .success(let features):
                self?.incidentFeatures = features
            case .failure(let error):
                self?.presentAlert(error: error)
            }
            dispatchGroup.leave()
        }
        dispatchGroup.notify(queue: .main) { [weak self] in
            guard let strongSelf = self else { return }

            let geometries = (strongSelf.facilityFeatures + strongSelf.incidentFeatures).compactMap { $0.geometry }
            if let extent = AGSGeometryEngine.combineExtents(ofGeometries: geometries) {
                strongSelf.mapView.setViewpointGeometry(extent, padding: 20)
            }

            strongSelf.solveRoutesButtonItem.isEnabled = true
        }

        return map
    }

    /// Queries for all the features from a given feature table.
    ///
    /// - Parameters:
    ///   - featureTable: The feature table whose features should be queried.
    ///   - completion: A closure executed upon success or failure.
    func queryAllFeatures(from featureTable: AGSFeatureTable, completion: @escaping (Result<[AGSFeature], Error>) -> Void) {
        featureTable.load { [unowned featureTable] (error) in
            if let error = error {
                completion(.failure(error))
            } else {
                let queryParameters = AGSQueryParameters()
                queryParameters.whereClause = "1=1"
                featureTable.queryFeatures(with: queryParameters) { (result, error) in
                    if let result = result {
                        completion(.success(result.featureEnumerator().allObjects))
                    } else if let error = error {
                        completion(.failure(error))
                    }
                }
            }
        }
    }

    /// Called in response to the Solve Routes button being tapped.
    @IBAction func solveRoutes() {
        solveRoutesButtonItem.isEnabled = false
        closestFacilityTask.defaultClosestFacilityParameters { [weak self] (parameters, error) in
            guard let self = self else { return }
            if let parameters = parameters {
                self.didGetClosestFacilityParameters(parameters)
            } else if let error = error {
                self.presentAlert(error: error)
                self.solveRoutesButtonItem.isEnabled = true
            }
        }
    }

    /// Called in response to the default closest facility paremters being
    /// generated successfully.
    ///
    /// - Parameter parameters: The parameters that were generated.
    func didGetClosestFacilityParameters(_ parameters: AGSClosestFacilityParameters) {
        let facilities = facilityFeatures.lazy
            .compactMap { $0.geometry as? AGSPoint }
            .map(AGSFacility.init(point:))
        parameters.setFacilities(Array(facilities))
        let incidents = incidentFeatures.lazy
            .compactMap { $0.geometry as? AGSPoint }
            .map(AGSIncident.init(point:))
        parameters.setIncidents(Array(incidents))
        self.closestFacilityTask.solveClosestFacility(with: parameters) { [weak self] (result, error) in
            guard let self = self else { return }
            if let result = result {
                self.didSolveClosestFacility(with: result)
            } else if let error = error {
                self.presentAlert(error: error)
                self.solveRoutesButtonItem.isEnabled = true
            }
        }
    }

    /// Called in response to the closest facility having been solved
    /// successfully.
    ///
    /// - Parameter result: The result of the solve closest facility operation.
    func didSolveClosestFacility(with result: AGSClosestFacilityResult) {
        // Create a graphic for the closest route to each facility.
        let routeGraphics = result.incidents.indices.compactMap { (incidentIndex) -> AGSGraphic? in
            guard let closestFacilityIndex = result.rankedFacilityIndexes(forIncidentIndex: incidentIndex)?.first as? Int else {
                return nil
            }

            let closestFacilityRoute = result.route(forFacilityIndex: closestFacilityIndex, incidentIndex: incidentIndex)
            let symbol = AGSSimpleLineSymbol(style: .solid, color: UIColor(red: 0, green: 0, blue: 1, alpha: 77 / 255), width: 5)
            return AGSGraphic(geometry: closestFacilityRoute?.routeGeometry, symbol: symbol)
        }
        // Add the graphics to the overlay.
        routesOverlay.graphics.addObjects(from: routeGraphics)
        resetButtonItem.isEnabled = true
    }

    /// Called in response to the Reset button being tapped.
    @IBAction func reset() {
        routesOverlay.graphics.removeAllObjects()

        resetButtonItem.isEnabled = false
        solveRoutesButtonItem.isEnabled = true
    }

    // MARK: UIViewController

    override func viewDidLoad() {
        super.viewDidLoad()

        // Add the source code button item to the right of navigation bar.
        (self.navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = [
            "FindClosestFacilityMultipleIncidentsServiceViewController"
        ]
    }
}

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