|
| 1 | +// Copyright 2023 Esri |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +import ArcGIS |
| 16 | +import SwiftUI |
| 17 | + |
| 18 | +struct FindClosestFacilityFromPointView: View { |
| 19 | + /// The view model for the sample. |
| 20 | + @StateObject private var model = Model() |
| 21 | + |
| 22 | + /// A Boolean value indicating whether a routing operation is in progress. |
| 23 | + @State private var isRouting = false |
| 24 | + |
| 25 | + /// A Boolean value indicating whether routing is currently disabled. |
| 26 | + @State private var routingIsDisabled = true |
| 27 | + |
| 28 | + /// A Boolean value indicating whether the error alert is showing. |
| 29 | + @State private var errorAlertIsShowing = false |
| 30 | + |
| 31 | + /// The error shown in the error alert. |
| 32 | + @State private var error: Error? { |
| 33 | + didSet { errorAlertIsShowing = error != nil } |
| 34 | + } |
| 35 | + |
| 36 | + var body: some View { |
| 37 | + MapViewReader { mapViewProxy in |
| 38 | + MapView(map: model.map, graphicsOverlays: [model.graphicsOverlay]) |
| 39 | + .overlay(alignment: .center) { |
| 40 | + if isRouting { |
| 41 | + ProgressView("Routing...") |
| 42 | + .padding() |
| 43 | + .background(.ultraThickMaterial) |
| 44 | + .cornerRadius(10) |
| 45 | + .shadow(radius: 50) |
| 46 | + } |
| 47 | + } |
| 48 | + .toolbar { |
| 49 | + ToolbarItemGroup(placement: .bottomBar) { |
| 50 | + Button("Solve Routes") { |
| 51 | + Task { |
| 52 | + do { |
| 53 | + isRouting = true |
| 54 | + defer { isRouting = false } |
| 55 | + |
| 56 | + try await model.solveRoutes() |
| 57 | + routingIsDisabled = true |
| 58 | + } catch { |
| 59 | + self.error = error |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + .disabled(routingIsDisabled) |
| 64 | + |
| 65 | + Spacer() |
| 66 | + |
| 67 | + Button("Reset") { |
| 68 | + model.graphicsOverlay.removeAllGraphics() |
| 69 | + routingIsDisabled = false |
| 70 | + } |
| 71 | + .disabled(model.graphicsOverlay.graphics.isEmpty) |
| 72 | + } |
| 73 | + } |
| 74 | + .task { |
| 75 | + // Get the extents of the layers on the map. |
| 76 | + await model.map.operationalLayers.load() |
| 77 | + let layerExtents = model.map.operationalLayers.compactMap(\.fullExtent) |
| 78 | + |
| 79 | + // Zoom to the extents to view the layers' features. |
| 80 | + guard let extent = GeometryEngine.combineExtents(of: layerExtents) else { return } |
| 81 | + await mapViewProxy.setViewpointGeometry(extent, padding: 30) |
| 82 | + } |
| 83 | + } |
| 84 | + .task { |
| 85 | + // Set up the closest facility parameters when the sample loads. |
| 86 | + do { |
| 87 | + try await model.configureClosestFacilityParameters() |
| 88 | + routingIsDisabled = false |
| 89 | + } catch { |
| 90 | + self.error = error |
| 91 | + } |
| 92 | + } |
| 93 | + .alert(isPresented: $errorAlertIsShowing, presentingError: error) |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +private extension FindClosestFacilityFromPointView { |
| 98 | + /// The view model for the sample. |
| 99 | + class Model: ObservableObject { |
| 100 | + /// A map with a streets relief basemap. |
| 101 | + let map = Map(basemapStyle: .arcGISStreetsRelief) |
| 102 | + |
| 103 | + /// The graphics overlay for the route graphics. |
| 104 | + let graphicsOverlay = GraphicsOverlay() |
| 105 | + |
| 106 | + /// The blue line symbol for the route graphics. |
| 107 | + private let routeSymbol = SimpleLineSymbol( |
| 108 | + style: .solid, |
| 109 | + color: UIColor(red: 0, green: 0, blue: 1, alpha: 77 / 255), |
| 110 | + width: 5 |
| 111 | + ) |
| 112 | + |
| 113 | + /// The task for finding the closest facility. |
| 114 | + private let closestFacilityTask = ClosestFacilityTask(url: .sanDiegoNetworkAnalysis) |
| 115 | + |
| 116 | + /// The parameters to be passed to the closest facility task. |
| 117 | + private var closestFacilityParameters: ClosestFacilityParameters? |
| 118 | + |
| 119 | + init() { |
| 120 | + // Create the feature layers and add them to the map. |
| 121 | + addFeatureLayer(tableURL: .facilitiesLayer, imageURL: .fireStationImage) |
| 122 | + addFeatureLayer(tableURL: .incidentsLayer, imageURL: .fireImage) |
| 123 | + } |
| 124 | + |
| 125 | + /// Creates the closest facility parameters and adds the facilities and incidents from the feature layers. |
| 126 | + func configureClosestFacilityParameters() async throws { |
| 127 | + // Create the default parameters from the closest facility task. |
| 128 | + async let parameters = try closestFacilityTask.makeDefaultParameters() |
| 129 | + |
| 130 | + // Get the feature layers on the map. |
| 131 | + await map.operationalLayers.load() |
| 132 | + let facilitiesLayer = map.operationalLayers.first( |
| 133 | + where: { $0.name == "sandiegofacilities" } |
| 134 | + ) as? FeatureLayer |
| 135 | + let incidentsLayer = map.operationalLayers.first( |
| 136 | + where: { $0.name == "sandiegoincidents" } |
| 137 | + ) as? FeatureLayer |
| 138 | + |
| 139 | + // Get the feature tables from the feature layers. |
| 140 | + guard let facilitiesTable = facilitiesLayer?.featureTable as? ArcGISFeatureTable, |
| 141 | + let incidentsTable = incidentsLayer?.featureTable as? ArcGISFeatureTable |
| 142 | + else { return } |
| 143 | + |
| 144 | + // Create query parameters that will return all the features. |
| 145 | + let queryParameters = QueryParameters() |
| 146 | + queryParameters.whereClause = "1=1" |
| 147 | + |
| 148 | + // Set the parameters' facilities and incidents using the tables. |
| 149 | + try await parameters.setFacilities( |
| 150 | + fromFeaturesIn: facilitiesTable, |
| 151 | + queryParameters: queryParameters |
| 152 | + ) |
| 153 | + try await parameters.setIncidents( |
| 154 | + fromFeaturesIn: incidentsTable, |
| 155 | + queryParameters: queryParameters |
| 156 | + ) |
| 157 | + closestFacilityParameters = try await parameters |
| 158 | + } |
| 159 | + |
| 160 | + /// Finds the closest facility routes for the incidents. |
| 161 | + func solveRoutes() async throws { |
| 162 | + guard let closestFacilityParameters else { return } |
| 163 | + |
| 164 | + // Get the closest facility result from the task using the parameters. |
| 165 | + let closestFacilityResult = try await closestFacilityTask.solveClosestFacility( |
| 166 | + using: closestFacilityParameters |
| 167 | + ) |
| 168 | + |
| 169 | + // Create a route graphic for each incident in the result. |
| 170 | + let incidentsIndices = closestFacilityResult.incidents.indices |
| 171 | + let routeGraphics = incidentsIndices.compactMap { incidentIndex -> Graphic? in |
| 172 | + // Get the index for the facility closest to the given incident and facility route. |
| 173 | + guard let closestFacilityIndex = closestFacilityResult.rankedIndexesOfFacilities( |
| 174 | + forIncidentAtIndex: incidentIndex |
| 175 | + ).first, |
| 176 | + let closestFacilityRoute = closestFacilityResult.route( |
| 177 | + toFacilityAtIndex: closestFacilityIndex, |
| 178 | + fromIncidentAtIndex: incidentIndex |
| 179 | + ) else { |
| 180 | + return nil |
| 181 | + } |
| 182 | + |
| 183 | + // Create a graphic using the route's geometry. |
| 184 | + return Graphic(geometry: closestFacilityRoute.routeGeometry, symbol: routeSymbol) |
| 185 | + } |
| 186 | + |
| 187 | + graphicsOverlay.addGraphics(routeGraphics) |
| 188 | + } |
| 189 | + |
| 190 | + /// Creates and adds a feature layer to the map. |
| 191 | + /// - Parameters: |
| 192 | + /// - tableURL: The URL to the feature table to create the feature layer from. |
| 193 | + /// - imageURL: The URL to the image to use as the layer's renderer. |
| 194 | + private func addFeatureLayer(tableURL: URL, imageURL: URL) { |
| 195 | + // Create a layer from the feature table URL. |
| 196 | + let featureTable = ServiceFeatureTable(url: tableURL) |
| 197 | + let featureLayer = FeatureLayer(featureTable: featureTable) |
| 198 | + |
| 199 | + // Create a simple renderer from the image URL and add it to the layer. |
| 200 | + let markerSymbol = PictureMarkerSymbol(url: imageURL) |
| 201 | + markerSymbol.width = 30 |
| 202 | + markerSymbol.height = 30 |
| 203 | + featureLayer.renderer = SimpleRenderer(symbol: markerSymbol) |
| 204 | + |
| 205 | + map.addOperationalLayer(featureLayer) |
| 206 | + } |
| 207 | + } |
| 208 | +} |
| 209 | + |
| 210 | +private extension URL { |
| 211 | + /// The URL to a network analysis server for San Diego, CA, USA on ArcGIS Online. |
| 212 | + static var sanDiegoNetworkAnalysis: URL { |
| 213 | + URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ClosestFacility")! |
| 214 | + } |
| 215 | + |
| 216 | + /// The URL to a San Diego facilities feature layer on ArcGIS Online. |
| 217 | + static var facilitiesLayer: URL { |
| 218 | + URL(string: "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/San_Diego_Facilities/FeatureServer/0")! |
| 219 | + } |
| 220 | + |
| 221 | + /// The URL to a San Diego facilities feature layer on ArcGIS Online. |
| 222 | + static var incidentsLayer: URL { |
| 223 | + URL(string: "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/San_Diego_Incidents/FeatureServer/0")! |
| 224 | + } |
| 225 | + |
| 226 | + /// The URL to an image of a fire station symbol on ArcGIS Online. |
| 227 | + static var fireStationImage: URL { |
| 228 | + URL(string: "https://static.arcgis.com/images/Symbols/SafetyHealth/FireStation.png")! |
| 229 | + } |
| 230 | + |
| 231 | + /// The URL to an image of a fire symbol on ArcGIS Online. |
| 232 | + static var fireImage: URL { |
| 233 | + URL(string: "https://static.arcgis.com/images/Symbols/SafetyHealth/esriCrimeMarker_56_Gradient.png")! |
| 234 | + } |
| 235 | +} |
0 commit comments