Skip to content

Edit geometries with programmatic reticle tool

View on GitHubSample viewer app

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.

EditGeometriesWithProgrammaticReticleTool

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 pass it to the MapView Composable.
  2. Start the GeometryEditor using GeometryEditor.start(GeometryType) to create a new geometry or GeometryEditor.start(Geometry) 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:
      • Use MapViewProxy.identify(GraphicsOverlay, ...) to identify graphics at the location of a tap.
      • Find the desired graphic in the resulting list.
      • Access the geometry associated with the graphic using Graphic.geometry - this will be used in the GeometryEditor.start(Geometry) method.
  3. Create a ProgrammaticReticleTool and set the GeometryEditor.tool.
  4. Launch coroutines to listen to GeometryEditor.hoveredElement and GeometryEditor.pickedUpElement.
    • These events can be used to determine the effect a button press will have and set the button text accordingly.
  5. Listen to tap events 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(...) to identify geometry editor elements at the location of the tap.
      • Find the desired element in the resulting list.
      • Depending on whether or not the element is a GeometryEditorVertex or GeometryEditorMidVertex use GeometryEditor.selectVertex(...) or GeometryEditor.selectMidVertex(...) to select it.
      • Update the viewpoint using MapViewProxy.setViewpointCenter(...).
  6. Enable and disable the vertex creation preview using ProgrammaticReticleTool.vertexCreationPreviewEnabled.
    • To prevent mid-vertex growth when hovered use ProgrammaticReticleTool.style.growEffect.applyToMidVertices.
  7. Check to see if undo and redo are possible during an editing session using GeometryEditor.canUndo and GeometryEditor.canRedo. If it's possible, use GeometryEditor.undo() and GeometryEditor.redo().
    • A picked up element can be returned to its previous position using GeometryEditor.cancelCurrentAction(). 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.
  8. Check whether the currently selected GeometryEditorElement can be deleted (GeometryEditor.selectedElement.canDelete). If the element can be deleted, delete using GeometryEditor.deleteSelectedElement().
  9. Call GeometryEditor.stop() to finish the editing session and store the Graphic. The GeometryEditor 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 GraphicsOverlay.
    • To create a new Graphic in the GraphicsOverlay:
      • Using Graphic(Geometry), create a new Graphic with the geometry returned by the GeometryEditor.stop() method.
      • Append the Graphic to the GraphicsOverlay(i.e. GraphicsOverlay.graphics.add(Graphic)).
    • 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

EditGeometriesWithProgrammaticReticleToolViewModel.ktEditGeometriesWithProgrammaticReticleToolViewModel.ktMainActivity.ktSettingsScreen.ktEditGeometriesWithProgrammaticReticleToolScreen.kt
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
/* 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
 *
 *    http://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.
 *
 */

package com.esri.arcgismaps.sample.editgeometrieswithprogrammaticreticletool.components

import android.app.Application
import androidx.compose.ui.unit.dp
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.arcgismaps.Color
import com.arcgismaps.geometry.Envelope
import com.arcgismaps.geometry.Geometry
import com.arcgismaps.geometry.GeometryType
import com.arcgismaps.geometry.Multipart
import com.arcgismaps.geometry.Multipoint
import com.arcgismaps.geometry.Point
import com.arcgismaps.geometry.Polygon
import com.arcgismaps.geometry.Polyline
import com.arcgismaps.mapping.ArcGISMap
import com.arcgismaps.mapping.BasemapStyle
import com.arcgismaps.mapping.Viewpoint
import com.arcgismaps.mapping.symbology.SimpleFillSymbol
import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
import com.arcgismaps.mapping.symbology.SimpleLineSymbol
import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
import com.arcgismaps.mapping.symbology.SimpleMarkerSymbol
import com.arcgismaps.mapping.symbology.SimpleMarkerSymbolStyle
import com.arcgismaps.mapping.symbology.Symbol
import com.arcgismaps.mapping.view.Graphic
import com.arcgismaps.mapping.view.GraphicsOverlay
import com.arcgismaps.mapping.view.ScreenCoordinate
import com.arcgismaps.mapping.view.SingleTapConfirmedEvent
import com.arcgismaps.mapping.view.geometryeditor.GeometryEditor
import com.arcgismaps.mapping.view.geometryeditor.GeometryEditorMidVertex
import com.arcgismaps.mapping.view.geometryeditor.GeometryEditorVertex
import com.arcgismaps.mapping.view.geometryeditor.ProgrammaticReticleTool
import com.arcgismaps.toolkit.geoviewcompose.MapViewProxy
import com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combineTransform
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch

private const val pinkneysGreenJson = """
    {"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}}
"""

private const val beechLodgeBoundaryJson = """
    {"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}}
"""

private const val treeMarkersJson = """
    {"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}}
"""

private val geometryTypes = mapOf(
    "Point" to GeometryType.Point,
    "Multipoint" to GeometryType.Multipoint,
    "Polyline" to GeometryType.Polyline,
    "Polygon" to GeometryType.Polygon,
)

private val Color.Companion.blue
    get() = fromRgba(0, 0, 255, 255)

private val Color.Companion.orangeRed
    get() = fromRgba(128, 128, 0, 255)

private val Color.Companion.transparentRed
    get() = fromRgba(255, 0, 0, 70)

class EditGeometriesWithProgrammaticReticleToolViewModel(app: Application) : AndroidViewModel(app) {

    private var reticleState = ReticleState.Default
    private var selectedGraphic: Graphic? = null
    private val programmaticReticleTool = ProgrammaticReticleTool()

    private val _allowVertexCreation = MutableStateFlow(true)
    val allowVertexCreation: StateFlow<Boolean> = _allowVertexCreation

    val arcGISMap = ArcGISMap(BasemapStyle.ArcGISImagery).apply {
        initialViewpoint = Viewpoint(latitude = 51.523806, longitude = -0.775395, scale = 4e4)
    }

    private val _startingGeometryType = MutableStateFlow("Polygon")
    val startingGeometryType: StateFlow<String> = _startingGeometryType

    private val _contextActionButtonText = MutableStateFlow("")
    val contextActionButtonText: StateFlow<String> = _contextActionButtonText

    private val _contextActionButtonEnabled = MutableStateFlow(true)
    val contextActionButtonEnabled: StateFlow<Boolean> = _contextActionButtonEnabled

    private val graphicsOverlay = GraphicsOverlay()
    val graphicsOverlays = listOf(graphicsOverlay)

    val geometryEditor = GeometryEditor().apply {
        tool = programmaticReticleTool
    }

    val messageDialogVM = MessageDialogViewModel()

    val mapViewProxy = MapViewProxy()

    // True if there is a selected element which is allowed to be deleted.
    val canDeleteSelectedElement = geometryEditor.selectedElement.map { selectedElement ->
        selectedElement?.canDelete ?: false
    }

    // True if either there is a picked up element or the editor's `canUndo` is true.
    val canUndoOrCancelInteraction = geometryEditor.pickedUpElement
        .map { it != null }
        .combineTransform(geometryEditor.canUndo) { a, b -> emit(a || b) }

    init {
        viewModelScope.run {
            launch {
                arcGISMap.load().onFailure { messageDialogVM.showMessageDialog(it) }
            }
            launch {
                geometryEditor.pickedUpElement.collect {
                    updateReticleState()
                }
            }
            launch {
                geometryEditor.hoveredElement.collect {
                    updateReticleState()
                }
            }
        }

        createInitialGraphics()
        updateContextActionButtonState() // set initial 'start editor' button text
    }

    /**
     * Stop the editor, discarding the current edit geometry.
     */
    fun onCancelButtonClick() {
        geometryEditor.stop()
        resetExistingEditState()
    }

    /**
     * Delete the currently selected element.
     *
     * Throws if there is no element or the current element can't be deleted.
     */
    fun onDeleteButtonPressed() {
        geometryEditor.deleteSelectedElement()
    }

    /**
     * Stops the editor, saving the edit geometry into a graphics overlay (updating the existing
     * graphic or adding a new one based on how the edit session was started).
     */
    fun onDoneButtonClick() {
        val geometry = geometryEditor.stop()
        if (geometry != null) {
            val graphic = selectedGraphic
            if (graphic != null) {
                graphic.geometry = geometry
            } else {
                graphicsOverlay.graphics.add(Graphic(geometry = geometry, symbol = geometry.defaultSymbol))
            }
        }
        resetExistingEditState()
    }

    /**
     * If the editor is not started, identifies a tapped graphic and starts the editor with its
     * geometry.
     *
     * If the editor is started, sets the viewpoint to the identified (mid-)vertex.
     */
    fun onMapViewTap(tapEvent: SingleTapConfirmedEvent) {
        viewModelScope.launch {
            if (geometryEditor.isStarted.value) {
                selectAndSetViewpointAt(tapEvent.screenCoordinate)
            } else {
                startWithIdentifiedGeometry(tapEvent.screenCoordinate)
            }
        }
    }

    /**
     * Performs different actions based on the editor's current hovered and picked up element, as
     * well as whether vertex creation is allowed. The behaviour is as follows:
     * - If the editor is stopped, starts it with a new geometry with the currently-selected geometry type
     * - Otherwise, if there is a picked up element, places it under the reticle
     * - Otherwise, if a vertex or mid-vertex is hovered over, picks it up
     * - Otherwise, inserts a new vertex at the reticle position
     */
    fun onContextActionButtonClick() {
        if (!geometryEditor.isStarted.value) {
            geometryEditor.start(geometryTypes.getOrDefault(startingGeometryType.value, GeometryType.Polygon))
            updateReticleState()
            return
        }

        when (reticleState) {
            ReticleState.Default, ReticleState.PickedUp -> programmaticReticleTool.placeElementAtReticle()
            ReticleState.HoveringVertex, ReticleState.HoveringMidVertex -> {
                programmaticReticleTool.selectElementAtReticle()
                programmaticReticleTool.pickUpSelectedElement()
            }
        }
    }

    /**
     * Redoes the last undone geometry editor action, if any
     */
    fun onRedoButtonPressed() {
        geometryEditor.redo()
    }

    /**
     * If there is a picked up element, places the element back in its original position.
     * Otherwise, undoes the last geometry editor action, if any.
     */
    fun onUndoButtonPressed() {
        if (geometryEditor.pickedUpElement.value != null) {
            geometryEditor.cancelCurrentAction()
        } else {
            geometryEditor.undo()
        }
    }

    /**
     * Enables or disables vertex creation, which affects the feedback lines and vertices, the
     * allowed context-button actions, and the presence of the grow effect for mid-vertices.
     */
    fun setAllowVertexCreation(newValue: Boolean) {
        _allowVertexCreation.value = newValue
        programmaticReticleTool.vertexCreationPreviewEnabled = newValue
        // Picking up a mid-vertex will lead to a new vertex being created. Only show feedback for
        // this if vertex creation is enabled.
        programmaticReticleTool.style.growEffect?.applyToMidVertices = newValue
        updateContextActionButtonState()
    }

    /**
     * Set the starting geometry type, used when not starting with an existing geometry.
     */
    fun setStartingGeometryType(newGeometryType: String) {
        _startingGeometryType.value = newGeometryType
    }

    /**
     * Identifies for a geometry editor element at the given screen coordinates. If a vertex
     * or mid-vertex is found, selects it and centers it in the view.
     */
    private suspend fun selectAndSetViewpointAt(tapPosition: ScreenCoordinate) {
        val identifyResult = mapViewProxy.identifyGeometryEditor(tapPosition, tolerance = 15.dp).getOrNull() ?: return
        val topElement = identifyResult.elements.firstOrNull() ?: return
        when (topElement) {
            is GeometryEditorVertex -> {
                geometryEditor.selectVertex(topElement.partIndex, topElement.vertexIndex)
                mapViewProxy.setViewpointCenter(topElement.point)
            }
            is GeometryEditorMidVertex -> {
                if (allowVertexCreation.value) {
                    geometryEditor.selectMidVertex(topElement.partIndex, topElement.segmentIndex)
                    mapViewProxy.setViewpointCenter(topElement.point)
                }
            }
            else -> { /* Only zoom to vertices and mid-vertices. */ }
        }
    }

    /**
     * Identifies for an existing graphic in the graphic overlay. If found, starts the geometry editor
     * using the graphic's geometry. Hides the existing graphic for the duration of the edit session.
     * Sets a new viewpoint center based on the graphic position (depending on what type of edits
     * are allowed).
     */
    private suspend fun startWithIdentifiedGeometry(tapPosition: ScreenCoordinate) {
        val identifyResult = mapViewProxy.identify(graphicsOverlay, tapPosition, tolerance = 15.dp).getOrNull() ?: return
        val graphic = identifyResult.graphics.firstOrNull() ?: return
        geometryEditor.start(graphic.geometry ?: return)

        graphic.geometry?.let { geometry ->
            if (allowVertexCreation.value) {
                mapViewProxy.setViewpointCenter(geometry.extent.center)
            } else {
                geometry.lastPoint?.let { lastPoint ->
                    mapViewProxy.setViewpointCenter(lastPoint)
                }
            }
        }

        graphic.isSelected = true
        graphic.isVisible = false
        selectedGraphic = graphic
        updateReticleState()
    }

    /**
     * Populates the graphics overlay with some starting graphics for editing.
     */
    private fun createInitialGraphics() {
        val treeMarkers = Geometry.fromJsonOrNull(treeMarkersJson) as Multipoint
        graphicsOverlay.graphics.add(Graphic(geometry = treeMarkers, symbol = treeMarkers.defaultSymbol))

        val beechLodgeBoundary = Geometry.fromJsonOrNull(beechLodgeBoundaryJson) as Polyline
        graphicsOverlay.graphics.add(Graphic(geometry = beechLodgeBoundary, symbol = beechLodgeBoundary.defaultSymbol))

        val pinkeysGreen = Geometry.fromJsonOrNull(pinkneysGreenJson) as Polygon
        graphicsOverlay.graphics.add(Graphic(geometry = pinkeysGreen, symbol = pinkeysGreen.defaultSymbol))
    }

    /**
     * Called whenever something happens that may change what the context-action button does
     * (e.g. editor stopping/starting, hovered or picked-up element changing).
     *
     * The private [reticleState] property decides what happens when the context-action button
     * is pressed, and is used to derive the text and enabled-ness of the button.
     */
    private fun updateReticleState() {
        if (geometryEditor.pickedUpElement.value != null) {
            reticleState = ReticleState.PickedUp
            updateContextActionButtonState()
            return
        }

        reticleState = when (geometryEditor.hoveredElement.value) {
            is GeometryEditorVertex -> ReticleState.HoveringVertex
            is GeometryEditorMidVertex -> ReticleState.HoveringMidVertex
            else -> ReticleState.Default
        }

        updateContextActionButtonState()
    }

    /**
     * Sets the text and enabled-ness of the context-action button based on the current reticle
     * state as well as whether vertex creation is allowed.
     *
     * Note that the enabled-ness of the button is used to prevent vertex insertion when vertex
     * creation is disabled.
     */
    private fun updateContextActionButtonState() {
        if (!geometryEditor.isStarted.value) {
            _contextActionButtonText.value = "Start Geometry Editor"
            _contextActionButtonEnabled.value = true
            return
        }

        if (allowVertexCreation.value) {
            _contextActionButtonEnabled.value = true
            _contextActionButtonText.value = when (reticleState) {
                ReticleState.Default -> "Insert Point"
                ReticleState.PickedUp -> "Drop Point"
                ReticleState.HoveringVertex, ReticleState.HoveringMidVertex -> "Pick Up Point"
            }
        } else {
            _contextActionButtonText.value = when (reticleState) {
                ReticleState.PickedUp -> "Drop Point"
                else -> "Pick Up Point"
            }
            _contextActionButtonEnabled.value =
                reticleState == ReticleState.HoveringVertex || reticleState == ReticleState.PickedUp
        }
    }

    /**
     * Clear the state for the currently selected graphic.
     */
    private fun resetExistingEditState() {
        selectedGraphic?.let { selectedGraphic ->
            selectedGraphic.isSelected = false
            selectedGraphic.isVisible = true
        }
        selectedGraphic = null
        updateContextActionButtonState()
    }

    private enum class ReticleState {
        Default,
        PickedUp,
        HoveringVertex,
        HoveringMidVertex,
    }
}

/**
 * A default symbol for the given geometry.
 */
private val Geometry.defaultSymbol: Symbol
    get() = when (this) {
        is Envelope -> throw IllegalStateException("Envelopes not supported by the geometry editor.")
        is Polygon -> SimpleFillSymbol(
            SimpleFillSymbolStyle.Solid,
            Color.transparentRed,
            outline = SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.black, 1f)
        )
        is Polyline -> SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.blue, 2f)
        is Multipoint -> SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.yellow, 5f)
        is Point -> SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Square, Color.orangeRed, 10f)
    }

/**
 * The last point of the first part of the given geometry (assumes there is at least one point).
 */
private val Geometry.lastPoint: Point?
    get() = when (this) {
        is Envelope -> throw IllegalStateException("Envelopes not supported by the geometry editor.")
        is Multipart -> parts.firstOrNull()?.endPoint
        is Point -> this
        is Multipoint -> points.lastOrNull()
    }

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