Snap geometry edits with utility network rules

View on GitHub

Use the Geometry Editor to edit geometries using utility network connectivity rules.

Screenshot of Snap geometry edits with utility network rules sample

Use case

A field worker can create new features in a utility network by editing and snapping the vertices of a geometry to existing features on a map. In a gas utility network, gas pipeline features can be represented with the polyline geometry type. Utility networks use geometric coincident-based connectivity to provide pathways for resources. Rule-based snapping uses utility network connectivity rules when editing features based on their asset type and asset group to help maintain network connectivity.

How to use the sample

To edit a geometry, tap a feature on the map to select it and press the edit button to start the geometry editor.

Tap the "Snap Sources" button to view and enable/disable the snap sources. To interactively snap a vertex to a feature or graphic, ensure that snapping is enabled for the relevant snap source, then drag a vertex to nearby an existing feature or graphic. If the existing feature or graphic has valid utility network connectivity rules for the asset type that is being created or edited, the edit position will be adjusted to coincide with (or snap to) edges and vertices of its geometry. Tap to place the vertex at the snapped location. Snapping will not occur when SnapRuleBehavior.rulesPreventSnapping is true, even when the source is enabled.

To discard changes and stop the geometry editor, press the Cancel (X) button. To save your edits, press the Save (✔️) button.

How it works

  1. Create a map and use its loadSettings to set featureTilingMode to enabledWithFullResolutionWhenSupported.
  2. Create a Geodatabase using the mobile geodatabase file location.
  3. Display Geodatabase.featureTables on the map using subtype feature layers.
  4. Create a GeometryEditor and connect it to a MapView.
  5. When editing a feature:
    1. Create a UtilityAssetType for the feature with UtilityNetwork.makeElement(arcGISFeature:terminal:) using the utility network from the geodatabase.
    2. Call SnapRules.rules(for:assetType:) to get the snap rules associated with the utility asset type.
    3. Use SnapSettings.syncSourceSettings(rules:sourceEnablingBehavior:) passing in the snap rules and SnapSourceEnablingBehavior.setFromRules to populate the SnapSettings.sourceSettings with SnapSourceSettings.
  6. Start the geometry editor with the feature's geometry or a Point geometry type.

Relevant API

  • FeatureLayer
  • Geometry
  • GeometryEditor
  • GeometryEditorStyle
  • GraphicsOverlay
  • MapView
  • SnapRuleBehavior
  • SnapRules
  • SnapSettings
  • SnapSource
  • SnapSourceEnablingBehavior
  • SnapSourceSettings
  • UtilityNetwork

About the data

This sample downloads the NapervilleGasUtilities item from ArcGIS Online automatically. The Naperville gas utilities mobile geodatabase contains a utility network with a set of connectivity rules that can be used to perform geometry edits with rule-based snapping.

Tags

edit, feature, geometry editor, graphics, layers, map, snapping, utility network

Sample Code

SnapGeometryEditsWithUtilityNetworkRulesView.swiftSnapGeometryEditsWithUtilityNetworkRulesView.swiftSnapGeometryEditsWithUtilityNetworkRulesView.Model.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
// Copyright 2025 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 SnapGeometryEditsWithUtilityNetworkRulesView: View {
    /// The display scale of this environment.
    @Environment(\.displayScale) private var displayScale

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

    /// The images representing the different snap rule behavior cases.
    @State private var ruleBehaviorImages: [SnapRuleBehavior?: Image] = [:]

    /// The various states of the sample.
    private enum SampleState: Equatable {
        /// The sample is being set up.
        case setup
        /// The given tap point is being identified.
        case identifying(tapPoint: CGPoint)
        /// The selected feature's geometry is being edited.
        case editing
        /// The feature's edits are being saved to its table.
        case saving
    }

    /// The current state of the sample.
    @State private var state = SampleState.setup

    /// A Boolean value indicating whether there are edits to be saved.
    @State private var canSave = false

    /// A Boolean value indicating whether snap sources list is showing.
    @State private var sourcesListIsPresented = false

    /// The error shown in the error alert.
    @State private var error: Error?

    /// The instruction text indicating the next step in the sample's workflow.
    private var instructionText: String {
        if state == .editing {
            canSave
            ? "Tap the save button to save the edits."
            : "Tap on the map to update the feature's geometry."
        } else {
            model.selectedElement == nil
            ? "Tap the map to select a feature."
            : "Tap the edit button to update the feature."
        }
    }

    var body: some View {
        MapViewReader { mapViewProxy in
            MapView(map: model.map, graphicsOverlays: [model.graphicsOverlay])
                .geometryEditor(model.geometryEditor)
                .onSingleTapGesture { screenPoint, _ in
                    state = .identifying(tapPoint: screenPoint)
                }
                .task(id: state) {
                    // Runs the async action related to the current sample state.
                    do {
                        switch state {
                        case .setup:
                            try await model.setUp()
                        case .identifying(let tapPoint):
                            let identifyResults = try await mapViewProxy.identifyLayers(
                                screenPoint: tapPoint,
                                tolerance: 5
                            )
                            try await model.selectFeature(from: identifyResults)
                        case .editing:
                            model.startEditing()

                            for await canUndo in model.geometryEditor.$canUndo {
                                canSave = canUndo
                            }
                        case .saving:
                            try await model.save()
                        }
                    } catch {
                        self.error = error
                    }
                }
                .errorAlert(presentingError: $error)
        }
        .overlay(alignment: .top) {
            VStack(alignment: .trailing, spacing: 0) {
                Text(instructionText)
                    .multilineTextAlignment(.center)
                    .frame(maxWidth: .infinity)
                    .padding(8)
                    .background(.thinMaterial, ignoresSafeAreaEdges: .horizontal)

                if let selectedElement = model.selectedElement {
                    VStack(alignment: .leading) {
                        LabeledContent("Asset Group:", value: selectedElement.assetGroup.name)
                        LabeledContent("Asset Type:", value: selectedElement.assetType.name)
                    }
                    .fixedSize()
                    .padding()
                    .background(.thinMaterial)
                    .clipShape(.rect(cornerRadius: 10))
                    .shadow(radius: 3)
                    .padding(8)
                    .transition(.move(edge: .trailing))

                    Spacer()

                    SnapRuleBehaviorLegend(images: ruleBehaviorImages)
                        .frame(maxWidth: .infinity)
                        .padding(8)
                        .background(.thinMaterial, ignoresSafeAreaEdges: .horizontal)
                }
            }
            .animation(.default, value: model.selectedElement == nil)
        }
        .toolbar {
            ToolbarItemGroup(placement: .bottomBar) {
                Button("Cancel", systemImage: "xmark") {
                    model.geometryEditor.stop()
                    model.resetSelection()
                }
                .disabled(model.selectedElement == nil)

                Spacer()

                Button("Snap Sources") {
                    sourcesListIsPresented = true
                }
                .disabled(model.snapSourceSettings.isEmpty)
                .popover(isPresented: $sourcesListIsPresented) {
                    SnapSourcesList(
                        settings: model.snapSourceSettings,
                        ruleBehaviorImages: ruleBehaviorImages
                    )
                    .presentationDetents([.fraction(0.5)])
                    .frame(idealWidth: 320, idealHeight: 390)
                }

                Spacer()

                if state == .editing {
                    Button("Save", systemImage: "checkmark") {
                        state = .saving
                    }
                    .disabled(!canSave)
                } else {
                    Button("Edit", systemImage: "pencil") {
                        state = .editing
                    }
                    .disabled(model.selectedElement == nil)
                }
            }
        }
        .task(id: displayScale) {
            // Creates an image from each rule behavior's symbol.
            for behavior in SnapRuleBehavior?.allCases {
                let swatch = try? await behavior.symbol.makeSwatch(scale: displayScale)
                ruleBehaviorImages[behavior] = swatch.map(Image.init(uiImage:))
            }
        }
    }
}

// MARK: - Helper Views

/// The legend for the different snap rule behavior cases.
private struct SnapRuleBehaviorLegend: View {
    /// The images representing the different snap rule behavior cases.
    let images: [SnapRuleBehavior?: Image]

    var body: some View {
        LabeledContent("Snapping") {
            HStack {
                ForEach(SnapRuleBehavior?.allCases, id: \.self) { behavior in
                    Label {
                        Text(behavior.label)
                    } icon: {
                        images[behavior]
                    }
                }
            }
        }
        .font(.footnote)
    }
}

/// A list for enabling and disabling snap source settings.
private struct SnapSourcesList: View {
    /// The snap source settings to show in the list.
    let settings: [SnapSourceSettings]

    /// The images representing the different snap rule behavior cases.
    let ruleBehaviorImages: [SnapRuleBehavior?: Image]

    /// The action to dismiss the view.
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        NavigationStack {
            Form {
                ForEach(Array(settings.enumerated()), id: \.offset) { _, settings in
                    let image = ruleBehaviorImages[settings.ruleBehavior]
                    SnapSourceSettingsToggle(settings: settings, image: image)
                }
            }
            .navigationTitle("Snap Sources")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .confirmationAction) {
                    Button("Done") { dismiss() }
                }
            }
        }
    }
}

/// A toggle for enabling and disabling a given snap source settings.
private struct SnapSourceSettingsToggle: View {
    /// The snap source settings to enable and disable.
    let settings: SnapSourceSettings

    /// The image to use in the toggle's label.
    let image: Image?

    /// A Boolean value indicating whether the toggle is enabled.
    @State private var isEnabled = false

    var body: some View {
        Toggle(isOn: $isEnabled) {
            Label {
                Text(settings.source.name)
            } icon: {
                image
            }
        }
        .onChange(of: isEnabled) { newValue in
            settings.isEnabled = newValue
        }
        .onAppear {
            isEnabled = settings.isEnabled
        }
    }
}

// MARK: - Extensions

extension SnapSource {
    /// The name of the snap source.
    var name: String {
        switch self {
        case let graphicsOverlay as GraphicsOverlay:
            graphicsOverlay.id
        case let layerContent as LayerContent:
            layerContent.name
        default:
            "\(self)"
        }
    }
}

extension Optional<SnapRuleBehavior> {
    fileprivate static var allCases: [Self] {
        return [.none, .rulesLimitSnapping, .rulesPreventSnapping]
    }

    /// The legend label for the snap rule behavior.
    fileprivate var label: String {
        switch self {
        case .rulesLimitSnapping: "Limited"
        case .rulesPreventSnapping: "Prevented"
        default: "Allowed"
        }
    }

    /// The symbol representing the snap rule behavior.
    var symbol: Symbol {
        switch self {
        case .rulesLimitSnapping:
            SimpleLineSymbol(style: .solid, color: .orange, width: 3)
        case .rulesPreventSnapping:
            SimpleLineSymbol(style: .solid, color: .red, width: 3)
        default:
            SimpleLineSymbol(style: .dash, color: .green, width: 3)
        }
    }
}

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