Show utility associations

View on GitHub

Create graphics for utility associations in a utility network.

Show utility associations sample

Use case

Visualizing utility associations can help you to better understand trace results and the topology of your utility network. For example, connectivity associations allow you to model connectivity between two junctions that don't have geometric coincidence (are not in the same location); structural attachment associations allow you to model equipment that may be attached to structures; and containment associations allow you to model features contained within other features.

How to use the sample

Pan and zoom around the map. Observe graphics that show utility associations between junctions.

How it works

  1. Create a UtilityNetwork with a feature service URL, add it to the map's utilityNetworks array, then load it.
  2. Add a FeatureLayer to the map for every UtilityNetworkSource of type edge or junction.
  3. Create a GraphicsOverlay for the utility associations.
  4. When the sample is opened and every time the viewpoint changes, do the following steps.
  5. Get the extent of the map view's target geometry by using MapView.onViewpointChanged(kind:).
  6. Get the associations that are within the current extent using UtilityNetwork.associations(forExtent:).
  7. Get the UtilityAssociation.Kind for each association.
  8. Create a Graphic using the Geometry property of the association and a preferred symbol.
  9. Add the graphic to the graphics overlay.

Relevant API

  • GraphicsOverlay
  • ServiceGeodatabase
  • UtilityAssociation
  • UtilityAssociation.Kind
  • UtilityNetwork

About the data

The feature service in this sample represents an electric network in Naperville, Illinois, which contains a utility network used to run the subnetwork-based trace.

Tags

associating, association, attachment, connectivity, containment, relationships

Sample Code

ShowUtilityAssociationsView.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
// 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 ShowUtilityAssociationsView: View {
    /// The view model for the sample.
    @StateObject private var model = Model()

    /// The current viewpoint of the map.
    @State private var viewpoint: Viewpoint = .initialViewpoint

    /// The scale of the viewpoint.
    @State private var scale: Double = .zero

    /// An image that represents an attachment symbol.
    @State private var attachmentImage: UIImage?

    /// An image that represents a connectivity symbol.
    @State private var connectivityImage: UIImage?

    /// The display scale of this environment.
    @Environment(\.displayScale) private var displayScale

    var body: some View {
        MapView(
            map: model.map,
            graphicsOverlays: [model.associationsOverlay]
        )
        .onScaleChanged {
            scale = $0
            Task { try await model.addAssociationGraphics(viewpoint: viewpoint, scale: scale) }
        }
        .onViewpointChanged(kind: .boundingGeometry) {
            viewpoint = $0
            Task { try await model.addAssociationGraphics(viewpoint: viewpoint, scale: scale) }
        }
        .task {
            try? await model.setup()
            try? await model.addAssociationGraphics(viewpoint: viewpoint, scale: scale)
        }
        .overlay(alignment: .topLeading) {
            legend
                .padding()
                .background(.thinMaterial)
                .cornerRadius(10)
                .shadow(radius: 3)
                .padding()
        }
    }
}

private extension ShowUtilityAssociationsView {
    /// The legend for the utility associations.
    var legend: some View {
        VStack {
            Label {
                Text("Attachment")
            } icon: {
                if let attachmentImage {
                    Image(uiImage: attachmentImage)
                } else {
                    Color.clear
                }
            }
            .task(id: displayScale) {
                attachmentImage = try? await Symbol.attachment
                    .makeSwatch(scale: displayScale)
            }
            Label {
                Text("Connectivity")
            } icon: {
                if let connectivityImage {
                    Image(uiImage: connectivityImage)
                } else {
                    Color.clear
                }
            }
            .task(id: displayScale) {
                connectivityImage = try? await Symbol.connectivity
                    .makeSwatch(scale: displayScale)
            }
        }
        .labelStyle(.titleAndIcon)
    }
}

private extension ShowUtilityAssociationsView {
    /// The model used to store the geo model and other expensive objects
    /// used in this view.
    @MainActor
    class Model: ObservableObject {
        // MARK: Properties

        /// The map with the utility network.
        let map = Map(basemapStyle: .arcGISTopographic)

        /// The utility network for this sample.
        private let network = UtilityNetwork(url: .utilityNetwork)

        /// A container for associations results.
        let associationsOverlay = makeAssociationsOverlay()

        /// A Boolean value indicating if the sample is authenticated.
        private var isAuthenticated: Bool {
            !ArcGISEnvironment.authenticationManager.arcGISCredentialStore.credentials.isEmpty
        }

        /// A Boolean value indicating if graphics are being added to the associations overlay.
        private var isAddingGraphics = false

        /// The max scale for the viewpoint.
        private var maxScale: Double { 2_000 }

        init() {
            map.initialViewpoint = .initialViewpoint
            map.addUtilityNetwork(network)
        }

        deinit {
            ArcGISEnvironment.authenticationManager.arcGISCredentialStore.removeAll()
        }

        // MARK: Methods

        /// Performs important tasks including adding credentials, loading and adding operational layers.
        func setup() async throws {
            try await ArcGISEnvironment.authenticationManager.arcGISCredentialStore.add(.publicSample)
            try await network.load()
            addLayers()
        }

        private func addLayers() {
            // Get all the edges and junctions in the network.
            guard let networkSources = network.definition?.networkSources else { return }
            let sourcesByType = Dictionary(grouping: networkSources, by: \.kind)

            // Add all edges that are not subnet lines to the map.
            let edgeLayers = sourcesByType[.edge, default: []]
                .filter { $0.usageKind != .subnetLine }
                .map { FeatureLayer(featureTable: $0.featureTable) }

            map.addOperationalLayers(edgeLayers)

            // Add all the junctions to the map.
            let junctionLayers = sourcesByType[.junction, default: []]
                .map { FeatureLayer(featureTable: $0.featureTable) }
            map.addOperationalLayers(junctionLayers)
        }

        static func makeAssociationsOverlay() -> GraphicsOverlay {
            let attachmentValue = UniqueValue(
                description: "Attachment",
                label: "",
                symbol: .attachment,
                values: [UtilityAssociation.Kind.attachment]
            )
            let connectivityValue = UniqueValue(
                description: "Connectivity",
                label: "",
                symbol: .connectivity,
                values: [UtilityAssociation.Kind.connectivity]
            )

            let renderer = UniqueValueRenderer(
                fieldNames: ["AssociationType"],
                uniqueValues: [attachmentValue, connectivityValue],
                defaultLabel: ""
            )

            let overlay = GraphicsOverlay()
            overlay.renderer = renderer
            return overlay
        }

        func addAssociationGraphics(viewpoint: Viewpoint, scale: Double) async throws {
            // Check if the current viewpoint is outside of the max scale.
            guard isAuthenticated, scale <= maxScale, !isAddingGraphics else { return }
            isAddingGraphics = true
            let extent = viewpoint.targetGeometry.extent
            // Get all of the associations in extent of the viewpoint.
            let associations = try await network.associations(forExtent: extent)
            let existingAssociationIDs = Set(
                associationsOverlay.graphics.compactMap { $0.attributes["GlobalId"] as? UUID }
            )
            let graphics: [Graphic] = associations
                .compactMap { association in
                    let associationID = association.globalID
                    guard !existingAssociationIDs.contains(associationID),
                          let symbol = symbol(for: association.kind) else { return nil }

                    return Graphic(
                        geometry: association.geometry,
                        attributes: [
                            "GlobalId": associationID,
                            "AssociationType": association.kind
                        ],
                        symbol: symbol
                    )
                }
            associationsOverlay.addGraphics(graphics)
            isAddingGraphics = false
        }

        func symbol(for associationKind: UtilityAssociation.Kind) -> Symbol? {
            switch associationKind {
            case .attachment:
                return Symbol.attachment
            case .connectivity:
                return Symbol.connectivity
            default:
                return nil
            }
        }
    }
}

private extension ArcGISCredential {
    /// The public credentials for the data in this sample.
    /// - Note: Never hardcode login information in a production application. This is done solely
    /// for the sake of the sample.
    static var publicSample: ArcGISCredential {
        get async throws {
            try await TokenCredential.credential(
                for: .utilityNetwork,
                username: "viewer01",
                password: "I68VGU^nMurF"
            )
        }
    }
}

private extension Symbol {
    /// A green dot.
    static var attachment: LineSymbol {
        SimpleLineSymbol(style: .dot, color: .green, width: 5)
    }

    /// A red dot.
    static var connectivity: LineSymbol {
        SimpleLineSymbol(style: .dot, color: .red, width: 5)
    }
}

private extension URL {
    /// The utility network for this sample.
    static var utilityNetwork: URL {
        URL(string: "https://sampleserver7.arcgisonline.com/server/rest/services/UtilityNetwork/NapervilleElectric/FeatureServer")!
    }
}

private extension Viewpoint {
    /// The initial viewpoint to be displayed when the sample is first opened.
    static var initialViewpoint: Viewpoint {
        .init(
            latitude: 41.8057655,
            longitude: -88.1489692,
            scale: 70.5310735
        )
    }
}

#Preview {
    NavigationStack {
        ShowUtilityAssociationsView()
    }
}

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