Skip to content

Edit geometries with programmatic reticle tool

View on GitHub

Use the Programmatic Reticle Tool to edit and create geometries with programmatic operations to facilitate customized workflows such as those using buttons rather than tap interactions.

Image of Edit geometries with programmatic reticle tool sample

Use case

A field worker can use a button driven workflow to mark important features on a map. They can digitize features like sample or observation locations, fences, pipelines, and building footprints using point, multipoint, polyline, and polygon geometries. To create and edit geometries, workers can use a vertex-based reticle tool to specify vertex locations by panning the map to position the reticle over a feature of interest. Using a button-driven workflow they can then place new vertices or pick up, move and drop existing vertices.

How to use the sample

To create a new geometry, select the geometry type you want to create (i.e. points, multipoints, polyline, or polygon) in the settings view. Press the button to start the geometry editor, pan the map to position the reticle then press the button to place a vertex. To edit an existing geometry, tap the geometry to be edited in the map and perform edits by positioning the reticle over a vertex and pressing the button to pick it up. The vertex can be moved by panning the map and dropped in a new position by pressing the button again.

Vertices can be selected and the viewpoint can be updated to their position by tapping them.

Vertex creation can be disabled using the switch in the settings view. When this switch is toggled off new vertex creation is prevented, existing vertices can be picked up and moved, but mid-vertices cannot be selected or picked up and will not grow when hovered. The feedback vertex and feedback lines under the reticle will also no longer be visible.

Use the buttons in the settings view to undo or redo changes made to the geometry and the cancel and done buttons to discard and save changes, respectively.

How it works

  1. Create a GeometryEditor and assign it to a map view with the geometryEditor view modifier.
  2. Use the start(withType:) method on the GeometryEditor to create a new geometry or start(withInitial:) to edit an existing geometry.
  • If using the Geometry Editor to edit an existing geometry, the geometry must be retrieved from the graphics overlay being used to visualize the geometry prior to calling the start method. To do this:
  • Create a MapViewReader to get the MapViewProxy and use it to identify graphics at the tapped location with identifyGraphicsOverlays(screenPoint:tolerance:returnPopupsOnly:maximumResultsPerLayer:).
  • Access the first graphic from the identify result IdentifyGraphicsOverlayResult.
  • Access the geometry associated with the Graphic using Graphic.geometry - this will be used in the GeometryEditor.start(withInitial:) method.
  1. Create a ProgrammaticReticleTool and set the geometry editor tool.
  2. Add event handlers to listen to GeometryEditor.HoveredElementChanged and GeometryEditorPickedUpElementChanged.
  • These events can be used to determine the effect a button press will have and set the button text accordingly.
  1. Use the onSingleTapGesture modifier to listen for tap events on the map view when the geometry editor is active to select and navigate to tapped vertices and mid-vertices.
  • To retrieve the tapped element and update the viewpoint:
  • Use MapViewProxy.identifyGeometryEditor(screenPoint:tolerance) to identify geometry editor elements at the location of the tap.
  • Access the first element from the IdentifyGeometryEditorResult as result.elements.first.
  • Depending on whether or not the element is a GeometryEditorVertex or GeometryEditorMidVertex use the selectVertexAt(partIndex:vertexIndex:) or the selectMidVertexAt(partIndex:segmentIndex:) methods on the geometry reader to select it.
  • Update the viewpoint using MapViewProxy.setViewpoint(_:duration:).
  1. Enable and disable the vertex creation preview using ProgrammaticReticleTool.vertexCreationPreviewIsEnabled.
  • To prevent mid-vertex growth when hovered use ProgrammaticReticleTool.Style.GrowEffect.appliesToMidVertices.
  1. Check to see if undo and redo are possible during an editing session using GeometryEditor.canUndo and GeometryEditor.canRedo. If it's possible, use the undo() and redo() methods on the geometry editor.
  • A picked up element can be returned to its previous position using cancelCurrentAction() on the geometry editor. This can be useful to undo a pick up without undoing any change to the geometry. Use the GeometryEditor.pickedUpElement property to check for a picked up element.
  1. Check whether the currently selected GeometryEditorElement can be deleted GeometryEditor.selectedElement.canBeDeleted. If the element can be deleted, delete using GeometryEditor.deleteSelectedElement().
  2. Call GeometryEditor.stop() to finish the editing session and store the Graphic. The geometry editor does not automatically handle the visualization of a geometry output from an editing session. This must be done manually by propagating the geometry returned into a graphic added to a graphics overlay.
  • To create a new graphic in the graphics overlay:
  • Use Graphic(geometry:), create a new Graphic with the geometry returned by the GeometryEditor.stop() method.
  • Append the graphic to the graphics overlay using GraphicsOverlay.addGraphic(_:).
  • To update the geometry underlying an existing Graphic in the GraphicsOverlay:
  • Replace the existing graphic's geometry property with the geometry returned by the GeometryEditor.stop() method.

Relevant API

  • Geometry
  • GeometryEditor
  • Graphic
  • GraphicsOverlay
  • MapView
  • ProgrammaticReticleTool

Additional information

The sample demonstrates a number of workflows which can be altered depending on desired app functionality:

  • picking up a hovered element combines selection and pick up, this can be separated into two steps to require selection before pick up.

  • tapping a vertex or mid-vertex selects it and updates the viewpoint to its position. This could be changed to not update the viewpoint or also pick up the element.

With the hovered and picked up element changed events and the programmatic APIs on the ProgrammaticReticleTool, a broad range of editing experiences can be implemented.

Tags

draw, edit, freehand, geometry editor, programmatic, reticle, sketch, vertex

Sample Code

EditGeometriesWithProgrammaticReticleToolView.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 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 // 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 EditGeometriesWithProgrammaticReticleToolView: View {  /// A map with an imagery basemap.  @State private var map: Map = {  let map = Map(basemapStyle: .arcGISImagery)  map.initialViewpoint = .ireland  return map  }()  /// The view model for this sample.  @State private var model = GeometryEditorModel()  /// The screen point to perform an identify operation.  @State private var identifyScreenPoint: CGPoint?   var body: some View {  VStack {  MapViewReader { mapView in  MapView(map: map, graphicsOverlays: [model.geometryOverlay])  .geometryEditor(model.geometryEditor)  .onSingleTapGesture { screenPoint, _ in  identifyScreenPoint = screenPoint  }  .task(id: identifyScreenPoint) {  guard let identifyScreenPoint else { return }  if model.isStarted {  await selectGeometryEditorElement(  at: identifyScreenPoint,  mapView: mapView  )  } else {  await startEditingGraphic(  at: identifyScreenPoint,  mapView: mapView  )  }  }  }  }  .toolbar {  ToolbarItem(placement: .topBarTrailing) {  GeometryEditorMenu(model: model)  }  ToolbarItem(placement: .bottomBar) {  Button(model.reticleState.label) {  model.handleReticleState()  }  .disabled(!model.geometryEditor.isStarted)  }  }  }   /// Selects the geometry editor element identified at the tap location to edit.  /// - Parameters:  /// - point: The screen coordinate of the geo view at which to identify.  /// - mapView: The map view proxy used to identify the screen point.  private func selectGeometryEditorElement(at point: CGPoint, mapView: MapViewProxy) async {  // Identify the geometry editor result at the tapped position.  let identifyResult = try? await mapView.identifyGeometryEditor(  screenPoint: point,  tolerance: 10  )  guard let element = identifyResult?.elements.first else { return }   // If the element is a vertex or mid-vertex, set the viewpoint to its position and select it.  switch element {  case let vertex as GeometryEditorVertex:  await mapView.setViewpoint(  Viewpoint(  center: element.extent.center,  scale: Viewpoint.ireland.targetScale  )  )  model.geometryEditor.selectVertexAt(  partIndex: vertex.partIndex,  vertexIndex: vertex.vertexIndex  )  case let midVertex as GeometryEditorMidVertex where model.allowsVertexCreation:  await mapView.setViewpoint(  Viewpoint(  center: element.extent.center,  scale: Viewpoint.ireland.targetScale  )  )  model.geometryEditor.selectMidVertexAt(  partIndex: midVertex.partIndex,  segmentIndex: midVertex.segmentIndex  )  default:  break  }  }   /// Starts editing the graphic identified at the tap location.  /// - Parameters:  /// - point: The screen coordinate of the geo view at which to identify.  /// - mapView: The map view proxy used to identify the screen point.  private func startEditingGraphic(at point: CGPoint, mapView: MapViewProxy) async {  // Identify graphics in the graphics overlay using the tapped position.  let results = try? await mapView.identifyGraphicsOverlays(  screenPoint: point,  tolerance: 10  )  guard let selectedGraphic = results?.first?.graphics.first,  let geometry = selectedGraphic.geometry else {  return  }   model.startEditing(with: selectedGraphic)   // If vertex creation is allowed, set the viewpoint to the center of the selected graphic's geometry.  // Otherwise, set the viewpoint to the end point of the first part of the geometry.  if model.allowsVertexCreation {  await mapView.setViewpoint(  Viewpoint(  center: geometry.extent.center,  scale: Viewpoint.ireland.targetScale  )  )  } else {  guard let center = model.selectedGraphic?.geometry?.lastPoint else { return }   await mapView.setViewpoint(  Viewpoint(  center: center,  scale: Viewpoint.ireland.targetScale  )  )  }  } }  /// A view that provides a menu for geometry editor functionality. private struct GeometryEditorMenu: View {  /// The model for the menu.  @Bindable var model: GeometryEditorModel   /// The currently selected element.  @State private var selectedElement: GeometryEditorElement?   /// The current geometry of the geometry editor.  @State private var geometry: Geometry?   var body: some View {  Menu("Geometry Editor", systemImage: "pencil.line") {  if !model.isStarted {  // If the geometry editor is not started, show the main menu.  mainMenuContent  } else {  // If the geometry editor is started, show the edit menu.  editMenuContent  .task {  for await geometry in model.geometryEditor.$geometry {  // Update geometry when there is an update.  self.geometry = geometry  }  }  .task {  for await element in model.geometryEditor.$selectedElement {  // Update selected element when there is an update.  selectedElement = element  }  }  .task {  for await _ in model.geometryEditor.$hoveredElement {  // Update reticle state when there is a hovered element update.  model.updateReticleState()  }  }  .task {  for await _ in model.geometryEditor.$pickedUpElement {  // Update reticle state when there is a hovered picked up element update.  model.updateReticleState()  }  }  }  }  } }  private extension GeometryEditorMenu {  /// The content of the main menu.  @ViewBuilder var mainMenuContent: some View {  Menu("Programmatic Reticle Tool") {  Button("New Point", systemImage: "smallcircle.filled.circle") {  model.startEditing(withType: Point.self)  }  Button("New Line", systemImage: "line.diagonal") {  model.startEditing(withType: Polyline.self)  }  Button("New Area", systemImage: "skew") {  model.startEditing(withType: Polygon.self)  }  Button("New Multipoint", systemImage: "hand.point.up.braille") {  model.startEditing(withType: Multipoint.self)  }  }   Divider()   Button("Delete All Geometries", systemImage: "trash", role: .destructive) {  model.deleteAllGeometries()  }  .disabled(!model.canClearGraphics)  }   /// The content of the editing menu.  @ViewBuilder var editMenuContent: some View {  Toggle("Allow vertex creation", isOn: $model.allowsVertexCreation)   Button("Undo", systemImage: "arrow.uturn.backward") {  if model.geometryEditor.pickedUpElement != nil {  model.geometryEditor.cancelCurrentAction()  } else {  model.geometryEditor.undo()  }  }  .disabled(!model.geometryEditor.canUndo)   Button("Redo", systemImage: "arrow.uturn.forward") {  model.geometryEditor.redo()  }  .disabled(!model.geometryEditor.canRedo)   Button("Delete Selected Element", systemImage: "xmark.square.fill") {  model.geometryEditor.deleteSelectedElement()  }  .disabled(deleteButtonIsDisabled)   Button("Clear Current Sketch", systemImage: "trash", role: .destructive) {  model.geometryEditor.clearGeometry()  }  .disabled(!canClearCurrentSketch)   Divider()   Button("Save Sketch", systemImage: "square.and.arrow.down") {  model.save()  }  .disabled(!canSave)   Button("Cancel Sketch", systemImage: "xmark") {  model.stop()  }  } }  private extension GeometryEditorMenu {  /// A Boolean value indicating whether the selection can be deleted.  ///  /// In some instances deleting the selection may be invalid. One example would be the mid vertex  /// of a line.  var deleteButtonIsDisabled: Bool {  guard let selectedElement else { return true }  return !selectedElement.canBeDeleted  }   /// A Boolean value indicating if the geometry can be saved to a graphics overlay.  var canSave: Bool {  return geometry?.sketchIsValid ?? false  }   /// A Boolean value indicating if the geometry can be cleared from the geometry editor.  var canClearCurrentSketch: Bool {  return geometry.map { !$0.isEmpty } ?? false  } }  /// An object that acts as a view model for the geometry editor menu. @MainActor @Observable private class GeometryEditorModel {  /// The geometry editor.  let geometryEditor = GeometryEditor()  /// The programmatic reticle tool.  private let reticleTool = ProgrammaticReticleTool()  /// The graphics overlay used to save geometries to.  let geometryOverlay = GraphicsOverlay(renderingMode: .dynamic)  /// The selected graphic to edit.  @ObservationIgnored var selectedGraphic: Graphic?  /// A Boolean value indicating if the initial graphics and saved sketches can be cleared.  private(set) var canClearGraphics = true  /// A Boolean value indicating if the geometry editor has started.  private(set) var isStarted = false  /// A Boolean value indicating if vertex creation is allowed.  var allowsVertexCreation = true {  didSet {  reticleTool.vertexCreationPreviewIsEnabled = allowsVertexCreation  reticleTool.style.growEffect?.appliesToMidVertices = allowsVertexCreation  }  }   /// The reticle state used to determine the current action of the programmatic reticle tool.  enum ReticleState {  case `default`, pickedUp, hoveringVertex, hoveringMidVertex   /// A human-readable label of the property.  var label: String {  switch self {  case .default: "Insert Point"  case .pickedUp: "Drop Point"  case .hoveringVertex: "Pick up point"  case .hoveringMidVertex: "Pick up point"  }  }  }   /// The programmatic reticle state.  var reticleState: ReticleState = .default   init() {  let pinkneysGreenGraphic = Graphic(geometry: .pinkneysGreen, symbol: .redArea())  let beechLodgeBoundaryGraphic = Graphic(geometry: .beechLodgeBoundary, symbol: .blueLine())  let treeMarkers = Graphic(geometry: .treeMarkers, symbol: .yellowCircle())  geometryOverlay.addGraphics([  pinkneysGreenGraphic,  beechLodgeBoundaryGraphic,  treeMarkers  ])   geometryEditor.tool = reticleTool  }   /// Saves the current geometry to the graphics overlay and stops editing.  /// - Precondition: Geometry's sketch must be valid.  func save() {  precondition(geometryEditor.geometry?.sketchIsValid ?? false)   if selectedGraphic != nil {  // Update geometry for edited graphic.  updateGraphic()  } else {  // Add new graphic.  addGraphic()  }   reticleState = .default  }   /// Updates the selected graphic with the current geometry.  private func updateGraphic() {  guard let selectedGraphic = selectedGraphic.take() else { return }  selectedGraphic.geometry = geometryEditor.stop()  isStarted = false  selectedGraphic.isVisible = true  }   /// Adds a new graphic for the current geometry to the graphics overlay.  private func addGraphic() {  let geometry = geometryEditor.geometry!  let graphic = Graphic(geometry: geometry, symbol: symbol(for: geometry))  geometryOverlay.addGraphic(graphic)  stop()  canClearGraphics = true  }   /// Removes the initial graphics and saved sketches on the graphics overlay.  func deleteAllGeometries() {  geometryOverlay.removeAllGraphics()  canClearGraphics = false  reticleState = .default  }   /// Starts editing with the specified tool and geometry type.  /// - Parameter geometryType: The type of geometry to draw.  func startEditing(withType geometryType: Geometry.Type) {  geometryEditor.start(withType: geometryType)  isStarted = true  reticleState = .default  }   /// Starts editing a given graphic with the geometry editor.  /// - Parameter graphic: The graphic to edit.  func startEditing(with graphic: Graphic) {  selectedGraphic = graphic  graphic.isVisible = false  let geometry = graphic.geometry!  geometryEditor.start(withInitial: geometry)  isStarted = true  updateReticleState()  }   /// Stops editing with the geometry editor.  func stop() {  geometryEditor.stop()  isStarted = false  if let selectedGraphic = selectedGraphic.take() {  selectedGraphic.isVisible = true  }  reticleState = .default  }   /// Returns the symbology for graphics saved to the graphics overlay.  /// - Parameter geometry: The geometry of the graphic to be saved.  /// - Returns: Either a marker or fill symbol depending on the type of provided geometry.  private func symbol(for geometry: Geometry) -> Symbol {  return switch geometry {  case is Point: .redSquare()  case is Multipoint: .yellowCircle()  case is Polyline: .blueLine()  case is ArcGIS.Polygon: .redArea()  default: fatalError("Unexpected geometry type")  }  }   /// Updates the reticle state based on the picked up and hovered elements.  func updateReticleState() {  reticleState = if geometryEditor.pickedUpElement != nil {  .pickedUp  } else if let hoveredElement = geometryEditor.hoveredElement {  if allowsVertexCreation {  // Vertices and mid-vertices can be picked up.  switch hoveredElement {  case is GeometryEditorVertex:  .hoveringVertex  case is GeometryEditorMidVertex:  .hoveringMidVertex  default:  .default  }  } else {  // Only vertices can be picked up, mid-vertices cannot be picked up.  switch hoveredElement {  case is GeometryEditorVertex:  .hoveringVertex  default:  .default  }  }  } else {  .default  }  }   /// Handles the reticle state by placing or picking up an element.  func handleReticleState() {  switch reticleState {  case .default, .pickedUp:  reticleTool.placeElementAtReticle()  case .hoveringVertex, .hoveringMidVertex:  reticleTool.selectElementAtReticle()  reticleTool.pickUpSelectedElement()  }  } }  private extension Geometry {  var lastPoint: Point? {  switch self {  case let multipart as any Multipart:  multipart.parts.last?.endPoint  case let multipoint as Multipoint:  multipoint.points.last  case let point as Point:  point  default:  nil  }  }   // swiftlint:disable force_try  static var pinkneysGreen: Geometry {  let json = Data(  """  {"rings":[[[-84843.262719916485,6713749.9329888355],[-85833.376589175183,6714679.7122141244],  [-85406.822347959576,6715063.9827222107],[-85184.329997390232,6715219.6195847588],  [-85092.653857582554,6715119.5391713539],[-85090.446872787768,6714792.7656492386],  [-84915.369168906298,6714297.8798246197],[-84854.295522911285,6714080.907587287],  [-84843.262719916485,6713749.9329888355]]],  "spatialReference":{"wkid":102100,"latestWkid":3857}}  """.utf8  )  return try! Polygon.fromJSON(json)  }   static var beechLodgeBoundary: Geometry {  let json = Data(  """  {"paths":[[[-87090.652708065536,6714158.9244240439],[-87247.362370337316,6714232.880689906],  [-87226.314032974493,6714605.4697726099],[-86910.499335316243,6714488.006312645],  [-86750.82198052686,6714401.1768307304],[-86749.846825938366,6714305.8450344801]]],  "spatialReference":{"wkid":102100,"latestWkid":3857}}  """.utf8  )  return try! Polyline.fromJSON(json)  }   static var treeMarkers: Geometry {  let json = Data(  """  {"points":[[-86750.751150056443,6713749.4529355941],[-86879.381793060631,6713437.3335486846],  [-87596.503104619667,6714381.7342108283],[-87553.257569537804,6714402.0910389507],  [-86831.019903597829,6714398.4128562529],[-86854.105933315877,6714396.1957954112],  [-86800.624094892439,6713992.3374453448]],  "spatialReference":{"wkid":102100,"latestWkid":3857}}"  """.utf8  )  return try! Multipoint.fromJSON(json)  }  // swiftlint:enable force_try }  private extension Symbol {  static func redSquare() -> Symbol {  SimpleMarkerSymbol(  style: .square,  color: .red,  size: 10  )  }   static func yellowCircle() -> Symbol {  SimpleMarkerSymbol(  style: .circle,  color: .yellow,  size: 5  )  }   static func blueLine() -> Symbol {  SimpleLineSymbol(  color: .blue,  width: 2  )  }   static func redArea() -> Symbol {  SimpleFillSymbol(  style: .solid,  color: .red.withAlphaComponent(0.3),  outline: SimpleLineSymbol(  style: .dash,  color: .black,  width: 1  )  )  } }  private extension Viewpoint {  /// A viewpoint centered at the island of Inis Meáin (Aran Islands) in Ireland.  static var ireland: Viewpoint {  Viewpoint(  center: Point(latitude: 51.523806, longitude: -0.775395),  scale: 2e4  )  } }  #Preview {  NavigationStack {  EditGeometriesWithProgrammaticReticleToolView()  } }

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