Find closest facility from point

View on GitHub

Find routes from several locations to the respective closest facility.

Image of find closest facility from point

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 a ClosestFacilityTask using a URL from an online service.
  2. Get the default set of ClosestFacilityParameters from the task: ClosestFacilityTask.makeDefaultParameters().
  3. Create a FeatureTable using ServiceFeatureTable.init(url:).
  4. Add a list of all facilities to the task parameters: ClosestFacilityParameters.setFacilities(fromFeaturesIn:queryParameters:).
  5. Add a list of all incidents to the task parameters: ClosestFacilityParameters.setIncidents(fromFeaturesIn:queryParameters:).
  6. Get ClosestFacilityResult by solving the task with the provided parameters: ClosestFacilityTask.solveClosestFacility(using:).
  7. Find the closest facility for each incident by iterating over the list of Incidents.
  8. Display the route as a Graphic using the ClosestFacilityRoute.routeGeometry.

Relevant API

  • ClosestFacilityParameters
  • ClosestFacilityResult
  • ClosestFacilityRoute
  • ClosestFacilityTask
  • Facility
  • Graphic
  • GraphicsOverlay
  • Incident

Tags

incident, network analysis, route, search

Sample Code

FindClosestFacilityFromPointView.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
229
230
231
232
233
234
235
236
237
// 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 FindClosestFacilityFromPointView: View {
    /// The view model for the sample.
    @StateObject private var model = Model()

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

    /// A Boolean value indicating whether routing is currently disabled.
    @State private var routingIsDisabled = true

    /// 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.graphicsOverlay])
                .overlay(alignment: .center) {
                    if isRouting {
                        ProgressView("Routing...")
                            .padding()
                            .background(.ultraThickMaterial)
                            .clipShape(.rect(cornerRadius: 10))
                            .shadow(radius: 50)
                    }
                }
                .toolbar {
                    ToolbarItemGroup(placement: .bottomBar) {
                        Button("Solve Routes") {
                            Task {
                                do {
                                    isRouting = true
                                    defer { isRouting = false }

                                    try await model.solveRoutes()
                                    routingIsDisabled = true
                                } catch {
                                    self.error = error
                                }
                            }
                        }
                        .disabled(routingIsDisabled || isRouting)

                        Spacer()

                        Button("Reset") {
                            model.graphicsOverlay.removeAllGraphics()
                            routingIsDisabled = false
                        }
                        .disabled(model.graphicsOverlay.graphics.isEmpty)
                    }
                }
                .task {
                    // Get the extents of the layers on the map.
                    await model.map.operationalLayers.load()
                    let layerExtents = model.map.operationalLayers.compactMap(\.fullExtent)

                    // Zoom to the extents to view the layers' features.
                    guard let extent = GeometryEngine.combineExtents(of: layerExtents) else { return }
                    await mapViewProxy.setViewpointGeometry(extent, padding: 30)
                }
        }
        .task {
            // Set up the closest facility parameters when the sample loads.
            do {
                try await model.configureClosestFacilityParameters()
                routingIsDisabled = false
            } catch {
                self.error = error
            }
        }
        .errorAlert(presentingError: $error)
    }
}

private extension FindClosestFacilityFromPointView {
    /// The view model for the sample.
    @MainActor
    class Model: ObservableObject {
        /// A map with a streets relief basemap.
        let map = Map(basemapStyle: .arcGISStreetsRelief)

        /// The graphics overlay for the route graphics.
        let graphicsOverlay = GraphicsOverlay()

        /// The blue line symbol for the route graphics.
        private let routeSymbol = SimpleLineSymbol(
            style: .solid,
            color: UIColor(red: 0, green: 0, blue: 1, alpha: 77 / 255),
            width: 5
        )

        /// The task for finding the closest facility.
        private let closestFacilityTask = ClosestFacilityTask(url: .sanDiegoNetworkAnalysis)

        /// The parameters to be passed to the closest facility task.
        private var closestFacilityParameters: ClosestFacilityParameters?

        init() {
            // Create the feature layers and add them to the map.
            addFeatureLayer(tableURL: .facilitiesLayer, imageURL: .fireStationImage)
            addFeatureLayer(tableURL: .incidentsLayer, imageURL: .fireImage)
        }

        /// Creates the closest facility parameters and adds the facilities and incidents from the feature layers.
        func configureClosestFacilityParameters() async throws {
            // Create the default parameters from the closest facility task.
            async let parameters = try closestFacilityTask.makeDefaultParameters()

            // Get the feature layers on the map.
            await map.operationalLayers.load()
            let facilitiesLayer = map.operationalLayers.first(
                where: { $0.name == "sandiegofacilities" }
            ) as? FeatureLayer
            let incidentsLayer = map.operationalLayers.first(
                where: { $0.name == "sandiegoincidents" }
            ) as? FeatureLayer

            // Get the feature tables from the feature layers.
            guard let facilitiesTable = facilitiesLayer?.featureTable as? ArcGISFeatureTable,
                  let incidentsTable = incidentsLayer?.featureTable as? ArcGISFeatureTable
            else { return }

            // Create query parameters that will return all the features.
            let queryParameters = QueryParameters()
            queryParameters.whereClause = "1=1"

            // Set the parameters' facilities and incidents using the tables.
            try await parameters.setFacilities(
                fromFeaturesIn: facilitiesTable,
                queryParameters: queryParameters
            )
            try await parameters.setIncidents(
                fromFeaturesIn: incidentsTable,
                queryParameters: queryParameters
            )
            closestFacilityParameters = try await parameters
        }

        /// Finds the closest facility routes for the incidents.
        func solveRoutes() async throws {
            guard let closestFacilityParameters else { return }

            // Get the closest facility result from the task using the parameters.
            let closestFacilityResult = try await closestFacilityTask.solveClosestFacility(
                using: closestFacilityParameters
            )

            // Create a route graphic for each incident in the result.
            let incidentsIndices = closestFacilityResult.incidents.indices
            let routeGraphics = incidentsIndices.compactMap { incidentIndex -> Graphic? in
                // Get the index for the facility closest to the given incident and facility route.
                guard let closestFacilityIndex = closestFacilityResult.rankedIndexesOfFacilities(
                    forIncidentAtIndex: incidentIndex
                ).first,
                      let closestFacilityRoute = closestFacilityResult.route(
                        toFacilityAtIndex: closestFacilityIndex,
                        fromIncidentAtIndex: incidentIndex
                      ) else {
                    return nil
                }

                // Create a graphic using the route's geometry.
                return Graphic(geometry: closestFacilityRoute.routeGeometry, symbol: routeSymbol)
            }

            graphicsOverlay.addGraphics(routeGraphics)
        }

        /// Creates and adds a feature layer to the map.
        /// - Parameters:
        ///   - tableURL: The URL to the feature table to create the feature layer from.
        ///   - imageURL: The URL to the image to use as the layer's renderer.
        private func addFeatureLayer(tableURL: URL, imageURL: URL) {
            // Create a layer from the feature table URL.
            let featureTable = ServiceFeatureTable(url: tableURL)
            let featureLayer = FeatureLayer(featureTable: featureTable)

            // Create a simple renderer from the image URL and add it to the layer.
            let markerSymbol = PictureMarkerSymbol(url: imageURL)
            markerSymbol.width = 30
            markerSymbol.height = 30
            featureLayer.renderer = SimpleRenderer(symbol: markerSymbol)

            map.addOperationalLayer(featureLayer)
        }
    }
}

private extension URL {
    /// The URL to a network analysis server for San Diego, CA, USA on ArcGIS Online.
    static var sanDiegoNetworkAnalysis: URL {
        URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ClosestFacility")!
    }

    /// The URL to a San Diego facilities feature layer on ArcGIS Online.
    static var facilitiesLayer: URL {
        URL(string: "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/San_Diego_Facilities/FeatureServer/0")!
    }

    /// The URL to a San Diego facilities feature layer on ArcGIS Online.
    static var incidentsLayer: URL {
        URL(string: "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/San_Diego_Incidents/FeatureServer/0")!
    }

    /// The URL to an image of a fire station symbol on ArcGIS Online.
    static var fireStationImage: URL {
        URL(string: "https://static.arcgis.com/images/Symbols/SafetyHealth/FireStation.png")!
    }

    /// The URL to an image of a fire symbol on ArcGIS Online.
    static var fireImage: URL {
        URL(string: "https://static.arcgis.com/images/Symbols/SafetyHealth/esriCrimeMarker_56_Gradient.png")!
    }
}

#Preview {
    NavigationStack {
        FindClosestFacilityFromPointView()
    }
}

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