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

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
- Create a map and use its
loadSettingsto setfeatureTilingModetoenabledWithFullResolutionWhenSupported. - Create a
Geodatabaseusing the mobile geodatabase file location. - Display
Geodatabase.featureTableson the map using subtype feature layers. - Create a
GeometryEditorand connect it to aMapView. - When editing a feature:
- Create a
UtilityAssetTypefor the feature withUtilityNetwork.makeElement(arcGISFeature:terminal:)using the utility network from the geodatabase. - Call
SnapRules.rules(for:assetType:)to get the snap rules associated with the utility asset type. - Use
SnapSettings.syncSourceSettings(rules:sourceEnablingBehavior:)passing in the snap rules andSnapSourceEnablingBehavior.setFromRulesto populate theSnapSettings.sourceSettingswithSnapSourceSettings.
- Create a
- Start the geometry editor with the feature’s geometry or a
Pointgeometry 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
// 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 ArcGISimport 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: (any 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) { settings.isEnabled = isEnabled } .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) } }}// 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 ArcGISimport Combineimport Foundation
extension SnapGeometryEditsWithUtilityNetworkRulesView { /// The view model for the sample. @MainActor final class Model: ObservableObject { // MARK: Properties
/// The utility element created from the selected feature. @Published private(set) var selectedElement: UtilityElement?
/// The settings for the sources that the selected feature can be snapped to. @Published private(set) var snapSourceSettings: [SnapSourceSettings] = []
/// A map with a streets night basemap initially centered on Naperville, IL, USA. let map: Map = { let map = Map(basemapStyle: .arcGISStreetsNight)
let point = Point(x: -9811055.1560284, y: 5131792.195025, spatialReference: .webMercator) map.initialViewpoint = Viewpoint(center: point, scale: 1e4)
// Enables full resolution to improve snapping accuracy. map.loadSettings.featureTilingMode = .enabledWithFullResolutionWhenSupported
return map }()
/// The graphics overlay containing an example graphic for snapping. let graphicsOverlay: GraphicsOverlay = { // Creates an example polyline graphic and adds it to the overlay. let polyline = try? Polyline.fromJSON(.polylineJSON) let graphic = Graphic(geometry: polyline)
let graphicsOverlay = GraphicsOverlay(graphics: [graphic]) graphicsOverlay.id = .graphics
let dashedGrayLinkSymbol = SimpleLineSymbol(style: .dash, color: .gray, width: 3) graphicsOverlay.renderer = SimpleRenderer(symbol: dashedGrayLinkSymbol)
return graphicsOverlay }()
/// The editor for editing the selected feature's geometry. let geometryEditor: GeometryEditor = { let geometryEditor = GeometryEditor() geometryEditor.snapSettings.isEnabled = true return geometryEditor }()
/// The tool for the geometry editor. private let vertexTool: GeometryEditorTool = {#if targetEnvironment(macCatalyst) VertexTool()#else ReticleVertexTool()#endif }()
/// The feature currently selected by the user. private var selectedFeature: ArcGISFeature?
/// The snap sources and their renderers for resetting the sample. private var snapSourceRenderers: [(Renderable, Renderer?)] = []
/// The geodatabase containing data for the Naperville gas utility network. private let geodatabase: Geodatabase = .napervilleGasUtilities()
/// The geodatabase's utility network. private var utilityNetwork: UtilityNetwork { geodatabase.utilityNetworks.first! }
// MARK: Methods
deinit { geodatabase.close()
let temporaryDirectoryURL = geodatabase.fileURL.deletingLastPathComponent() try? FileManager.default.removeItem(at: temporaryDirectoryURL) }
/// Sets up the map and layers for the sample. func setUp() async throws { try await geodatabase.load()
map.addUtilityNetwork(utilityNetwork) try await utilityNetwork.load()
// Creates and adds subtype feature layers to the map. let lineLayer = SubtypeFeatureLayer( featureTable: geodatabase.featureTable(named: .pipelineLine)! ) let deviceLayer = SubtypeFeatureLayer( featureTable: geodatabase.featureTable(named: "PipelineDevice")! ) let junctionLayer = SubtypeFeatureLayer( featureTable: geodatabase.featureTable(named: "PipelineJunction")! )
map.addOperationalLayers([lineLayer, deviceLayer, junctionLayer]) await map.operationalLayers.load()
// Turns off most of the subtype sublayers to reduce clutter on the map. let visibleSublayerNames: Set = [ .distributionPipe, .servicePipe, "Excess Flow Valve", "Controllable Tee" ] let sublayers = lineLayer.subtypeSublayers + deviceLayer.subtypeSublayers for sublayer in sublayers where !visibleSublayerNames.contains(sublayer.name) { sublayer.isVisible = false } }
/// Selects a feature from a given list of identify layer results. /// - Parameter identifyResults: The identify layer results to get the feature from. func selectFeature(from identifyResults: [IdentifyLayerResult]) async throws { resetSelection()
// Gets the first subtype feature with a point geometry. let sublayerGeoElement = identifyResults .flatMap { $0.sublayerResults.flatMap(\.geoElements) } .first(where: { $0 is ArcGISFeature && $0.geometry is Point })
// Creates a utility element from the feature and uses it to set up the snap sources. if let feature = sublayerGeoElement as? ArcGISFeature, let featureLayer = feature.table?.layer as? FeatureLayer, let utilityElement = utilityNetwork.makeElement(arcGISFeature: feature) { selectedElement = utilityElement selectedFeature = feature featureLayer.selectFeature(feature)
try await setUpSnapSourcesSettings(using: utilityElement.assetType) } }
/// Clears the feature selection and resets the rendering. func resetSelection() { if let featureLayer = selectedFeature?.table?.layer as? FeatureLayer { featureLayer.clearSelection() featureLayer.resetFeaturesVisible() }
selectedFeature = nil selectedElement = nil
// Resets all the snap sources to use their default renderer. for (source, renderer) in snapSourceRenderers { source.renderer = renderer } snapSourceRenderers.removeAll(keepingCapacity: true) snapSourceSettings.removeAll(keepingCapacity: true) }
/// Saves the geometry edits to the selected feature's table and resets the selection. func save() async throws { if let selectedFeature { selectedFeature.geometry = geometryEditor.stop() try await selectedFeature.table?.update(selectedFeature) }
resetSelection() }
/// Starts a geometry editing session with the selected feature. func startEditing() { guard let selectedFeature, let geometry = selectedFeature.geometry else { return }
// Hides the selected feature on the layer. if let featureTable = selectedFeature.table as? ArcGISFeatureTable { if let featureLayer = featureTable.layer as? FeatureLayer { featureLayer.setVisible(false, for: selectedFeature) }
// Gets the selected feature's symbol and uses it to set the tool's style. let symbol = featureTable.layerInfo?.drawingInfo?.renderer?.symbol(for: selectedFeature) vertexTool.style.vertexSymbol = symbol vertexTool.style.feedbackVertexSymbol = symbol vertexTool.style.selectedVertexSymbol = symbol vertexTool.style.vertexTextSymbol = nil }
geometryEditor.tool = vertexTool geometryEditor.start(withInitial: geometry) }
/// Sets up the snap source settings. /// - Parameter assetType: The utility asset type for selected feature. private func setUpSnapSourcesSettings(using assetType: UtilityAssetType) async throws { // Analyzes the utility network to get the snap rules for the asset type. let rules = try await SnapRules.rules(for: utilityNetwork, assetType: assetType)
// Syncs snap source settings using the snap rules. let snapSettings = geometryEditor.snapSettings try snapSettings.syncSourceSettings(rules: rules, sourceEnablingBehavior: .setFromRules) snapSourceSettings = filterSnapSourceSettings(snapSettings.sourceSettings)
// Sets the snap source renderers to use their rule behavior symbol. snapSourceRenderers = snapSourceSettings.compactMap { settings in guard let renderedSource = settings.source as? Renderable else { return nil }
let defaultRender = renderedSource.renderer renderedSource.renderer = SimpleRenderer(symbol: settings.ruleBehavior.symbol) settings.isEnabled = true
return (renderedSource, defaultRender) } }
/// Recursively filters a list of snap source settings. /// - Parameter settings: The list of snap source settings to filter. /// - Returns: The snap sources settings used by this sample. private func filterSnapSourceSettings( _ settings: [SnapSourceSettings] ) -> [SnapSourceSettings] { let sourceNames: Set<String> = [.distributionPipe, .graphics, .pipelineLine, .servicePipe] return settings.reduce(into: []) { result, setting in guard sourceNames.contains(setting.source.name) else { return }
if setting.source is SubtypeFeatureLayer { let childSourceSettings = filterSnapSourceSettings(setting.childSourceSettings) result.append(contentsOf: childSourceSettings) } else { result.append(setting) } } } }}
// MARK: - Extensions
/// An object that has a renderer.private protocol Renderable: AnyObject { var renderer: Renderer? { get set }}extension GraphicsOverlay: Renderable {}extension SubtypeSublayer: Renderable {}
private extension String { static let distributionPipe = "Distribution Pipe" static let graphics = "Graphics" static let pipelineLine = "PipelineLine" static let servicePipe = "Service Pipe"}
private extension Data { /// The JSON for the example graphic's geometry. static var polylineJSON: Data { Data( "{\"paths\":[[[-9811826.6810284462,5132074.7700250093],[-9811786.4643617794,5132440.9533583419],[-9811384.2976951133,5132354.1700250087],[-9810372.5310284477,5132360.5200250093],[-9810353.4810284469,5132066.3033583425]]],\"spatialReference\":{\"wkid\":102100,\"latestWkid\":3857}}".utf8 ) }}
private extension Geodatabase { /// Returns a temporary geodatabase with gas utility network data for Naperville. static func napervilleGasUtilities() -> Geodatabase { let temporaryGeodatabaseURL = try! FileManager.default .url( for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: .temporaryDirectory, create: true ) .appending(component: "NapervilleGasUtilities.geodatabase")
try? FileManager.default.copyItem( at: .napervilleGasUtilitiesGeodatabase, to: temporaryGeodatabaseURL )
return Geodatabase(fileURL: temporaryGeodatabaseURL) }}
private extension URL { /// The URL to the local geodatabase file containing a data for the Naperville gas utility network. static var napervilleGasUtilitiesGeodatabase: URL { Bundle.main.url(forResource: "NapervilleGasUtilities", withExtension: "geodatabase")! }}