Show service area

View on GitHub

Find the service area within a network from a given point.

Image of show service area sample

Use case

A service area shows locations that can be reached from a facility based off a certain impedance, such as travel time or distance. Barriers can increase impedance by either adding to the time it takes to pass through the barrier or by altogether preventing passage.

You might calculate the region around a hospital in which ambulances can service in 30 minutes or less.

How to use the sample

In order to find any service areas at least one facility needs to be added to the map view.

  • To add a facility, tap or click the facility button and then anywhere on the map.
  • To add a barrier, tap or click the barrier button and then multiple locations on map. Tap or click the barrier button again to finish drawing barrier. Tapping or clicking any other button will also stop the barrier from drawing.
  • To show service areas around facilities that were added, tap or click the Service Areas button.
  • The reset button clears all graphics and resets the service area task.

How it works

  1. Create a new ServiceAreaTask from a network service.
  2. Create default ServiceAreaParameters from the service area task.
  3. Set the parameters to return polygons (true) to return all service areas.
  4. Add a ServiceAreaFacility to the parameters.
  5. Get the ServiceAreaResult by solving the service area task using the parameters.
  6. Get any ServiceAreaPolygons that were returned using ServiceAreaResult.resultPolygons(forFacilityAtIndex:).
  7. Display the service area polygons as graphics in a GraphicsOverlay on the MapView.

Relevant API

  • PolylineBarrier
  • ServiceAreaFacility
  • ServiceAreaParameters
  • ServiceAreaPolygon
  • ServiceAreaResult
  • ServiceAreaTask

Tags

barriers, facilities, impedance, logistics, routing

Sample Code

ShowServiceAreaView.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
238
239
240
241
242
243
244
245
246
247
248
249
250
// Copyright 2024 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 ShowServiceAreaView: View {
    // MARK: - View

    /// The currently selected graphic type.
    ///
    /// Used to track whether to add facilities or barriers to the map.
    @State private var selectedGraphicType: GraphicType = .facility
    /// The error shown in the error alert.
    @State private var error: Error?
    /// First time break property set in first stepper.
    @State private var firstTimeBreak: Int = 3
    /// Second time break property set in second stepper.
    @State private var secondTimeBreak: Int = 8
    /// A Boolean value indicating whether the time breaks settings are presented.
    @State private var settingsArePresented = false
    /// A Boolean value indicating whether the service area is being solved.
    @State private var isSolvingServiceArea = false

    /// The data model for the sample.
    @StateObject private var model = Model()

    var body: some View {
        MapView(map: model.map, graphicsOverlays: model.graphicsOverlays)
            .onSingleTapGesture { _, point in
                switch selectedGraphicType {
                case .facility:
                    model.addFacilityGraphic(at: point)
                case .barrier:
                    model.addBarrierGraphic(at: point)
                }
            }
            .toolbar {
                ToolbarItemGroup(placement: .bottomBar) {
                    Picker("Mode", selection: $selectedGraphicType) {
                        ForEach(GraphicType.allCases, id: \.self) {
                            Text($0.label)
                        }
                    }
                    .pickerStyle(.segmented)
                    Spacer()
                    Button("Time Breaks", systemImage: "gear") {
                        settingsArePresented = true
                    }
                    .popover(isPresented: $settingsArePresented) {
                        NavigationStack {
                            Form {
                                Stepper("First: \(firstTimeBreak)", value: $firstTimeBreak, in: 1...15)
                                Stepper("Second: \(secondTimeBreak)", value: $secondTimeBreak, in: 1...15)
                            }
                            .navigationTitle("Time Breaks")
                            .navigationBarTitleDisplayMode(.inline)
                            .toolbar {
                                ToolbarItem(placement: .confirmationAction) {
                                    Button("Done") { settingsArePresented = false }
                                }
                            }
                        }
                        .presentationDetents([.fraction(0.25)])
                        .frame(idealWidth: 320, idealHeight: 160)
                    }
                    Spacer()
                    Button("Service Area") {
                        Task {
                            isSolvingServiceArea = true
                            do {
                                try await model.showServiceArea(
                                    timeBreaks: [Double(firstTimeBreak), Double(secondTimeBreak)]
                                )
                            } catch {
                                self.error = error
                            }
                            isSolvingServiceArea = false
                        }
                    }
                    .disabled(isSolvingServiceArea)
                    Spacer()
                    Button("Clear", systemImage: "trash") {
                        model.removeAllGraphics()
                    }
                }
            }
            .errorAlert(presentingError: $error)
    }
}

private extension ShowServiceAreaView {
    // MARK: - GraphicType

    enum GraphicType: Equatable, CaseIterable {
        case facility, barrier

        /// The string representation of this graphic type.
        var label: String {
            switch self {
            case .barrier: "Barriers"
            case .facility: "Facilities"
            }
        }
    }
}

private extension ShowServiceAreaView {
    // MARK: - Model

    @MainActor
    class Model: ObservableObject {
        /// A map with terrain style centered over San Diego.
        let map: Map = {
            let map = Map(basemapStyle: .arcGISTerrain)
            map.initialViewpoint = Viewpoint(
                center: Point(
                    x: -13041154,
                    y: 3858170,
                    spatialReference: .webMercator
                ),
                scale: 60_000
            )
            return map
        }()

        private let facilitiesGraphicsOverlay: GraphicsOverlay = {
            let facilitiesGraphicsOverlay = GraphicsOverlay()
            let facilitySymbol = PictureMarkerSymbol(image: .pinBlueStar)
            // Offsets symbol in Y to align image properly.
            facilitySymbol.offsetY = 21
            // Assigns renderer on facilities graphics overlay using the picture marker symbol.
            facilitiesGraphicsOverlay.renderer = SimpleRenderer(symbol: facilitySymbol)
            return facilitiesGraphicsOverlay
        }()

        private let barriersGraphicsOverlay: GraphicsOverlay = {
            let barriersGraphicsOverlay = GraphicsOverlay()
            let barrierSymbol = SimpleFillSymbol(style: .diagonalCross, color: .red, outline: nil)
            // Sets symbol on barrier graphics overlay using renderer.
            barriersGraphicsOverlay.renderer = SimpleRenderer(symbol: barrierSymbol)
            return barriersGraphicsOverlay
        }()

        private let serviceAreaGraphicsOverlay = GraphicsOverlay()

        /// The graphics overlays used by this model.
        var graphicsOverlays: [GraphicsOverlay] {
            return [facilitiesGraphicsOverlay, barriersGraphicsOverlay, serviceAreaGraphicsOverlay]
        }

        private let serviceAreaTask = ServiceAreaTask(url: .serviceArea)

        private var serviceAreaParameters: ServiceAreaParameters!

        /// On user tapping on screen it add a facility graphic to the facilities overlay on the map at that point.
        /// - Parameter point: The coordinates for the graphic.
        func addFacilityGraphic(at point: Point) {
            let graphic = Graphic(geometry: point)
            facilitiesGraphicsOverlay.addGraphic(graphic)
        }

        /// On user tapping on screen it add a barrier graphic to the barriers overlay on the map at that point.
        /// - Parameter point: The coordinates for the graphic.
        func addBarrierGraphic(at point: Point) {
            let bufferedGeometry = GeometryEngine.buffer(around: point, distance: 500)
            let graphic = Graphic(geometry: bufferedGeometry)
            barriersGraphicsOverlay.addGraphic(graphic)
        }

        /// Gets the service area data and then renders the service area on the map.
        /// - Parameter timeBreaks: Double values that user sets for the impedance cutoffs.
        func showServiceArea(timeBreaks: [Double]) async throws {
            if serviceAreaParameters == nil {
                serviceAreaParameters = try await serviceAreaTask.makeDefaultParameters()
                serviceAreaParameters.geometryAtOverlap = .dissolve
            }
            serviceAreaGraphicsOverlay.removeAllGraphics()
            // Add the graphics to the overlays with their respective geometry types.
            serviceAreaParameters.setFacilities(
                facilitiesGraphicsOverlay.graphics.lazy.map { .init(point: $0.geometry as! Point) }
            )
            serviceAreaParameters.setPolygonBarriers(
                barriersGraphicsOverlay.graphics.lazy.map { .init(polygon: $0.geometry as! ArcGIS.Polygon) }
            )
            serviceAreaParameters.removeAllDefaultImpedanceCutoffs()
            serviceAreaParameters.addDefaultImpedanceCutoffs(timeBreaks)
            try await renderServiceAreaPolygons()
        }

        /// Asynchronously uses the service area task to solve for the service area using the parameters and then iterates through resulting
        /// polygons and creates a graphic which is added to the overlay for rendering.
        private func renderServiceAreaPolygons() async throws {
            let result = try await serviceAreaTask.solveServiceArea(using: serviceAreaParameters)
            let polygons = result.resultPolygons(forFacilityAtIndex: 0)
            for (offset, polygon) in polygons.enumerated() {
                let fillSymbol = makeServiceAreaSymbol(isFirst: offset == .zero)
                let graphic = Graphic(geometry: polygon.geometry, symbol: fillSymbol)
                serviceAreaGraphicsOverlay.addGraphic(graphic)
            }
        }

        /// Resets the graphics, removes the barriers, facilities and service area.
        func removeAllGraphics() {
            serviceAreaGraphicsOverlay.removeAllGraphics()
            facilitiesGraphicsOverlay.removeAllGraphics()
            barriersGraphicsOverlay.removeAllGraphics()
        }

        /// Sets the symbols drawn on that map for given selection.
        /// - Parameter isFirst: Tracks which element in is first in order to correctly set the color for the symbols.
        /// - Returns: Returns the symbol.
        private func makeServiceAreaSymbol(isFirst: Bool) -> Symbol {
            let lineSymbolColor: UIColor
            let fillSymbolColor: UIColor
            if isFirst {
                lineSymbolColor = UIColor(red: 0.4, green: 0.4, blue: 0, alpha: 0.3)
                fillSymbolColor = UIColor(red: 0.8, green: 0.8, blue: 0, alpha: 0.3)
            } else {
                lineSymbolColor = UIColor(red: 0, green: 0.4, blue: 0, alpha: 0.3)
                fillSymbolColor = UIColor(red: 0, green: 0.8, blue: 0, alpha: 0.3)
            }
            let outline = SimpleLineSymbol(style: .solid, color: lineSymbolColor, width: 2)
            return SimpleFillSymbol(style: .solid, color: fillSymbolColor, outline: outline)
        }
    }
}

#Preview {
    ShowServiceAreaView()
}

private extension URL {
    // MARK: - URLs

    static var serviceArea: URL {
        URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ServiceArea")!
    }
}

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