Snap geometry edits

View on GitHubSample viewer app

Use the Geometry Editor to edit a geometry and align it to existing geometries on a map.

Image of Snap geometry edits

Use case

A field worker can create new features by editing and snapping the vertices of a geometry to existing features on a map. In a water distribution network, service line features can be represented with the polyline geometry type. By snapping the vertices of a proposed service line to existing features in the network, an exact footprint can be identified to show the path of the service line and what features in the network it connects to. The feature layer containing the service lines can then be accurately modified to include the proposed line.

How to use the sample

To create a geometry, press the create button to choose the geometry type you want to create (i.e. points, multipoints, polyline, or polygon) and interactively tap and drag on the map view to create the geometry.

Snap settings can be configured by enabling and disabling snapping, feature snapping, geometry guides, and snap sources.

To interactively snap a vertex to a feature or graphic, ensure that snapping is enabled for the relevant snap source and move the map position of the reticle to nearby an existing feature or graphic. When the reticle is close to that existing geoelement, 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.

To edit a geometry, tap the geometry to be edited in the map and then edit the geometry by tapping and moving its vertices and snapping them to nearby features or graphics.

To edit a vertex using the reticle, tap when the reticle is located over the vertex, drag the map to move the position of the reticle, then tap a second time to place the vertex.

To undo changes made to the geometry, press the undo button.

To delete a vertex, tap when the reticle is located over the vertex and then press the delete button.

To save your edits, press the save button.

How it works

  1. Create a Map from the URL and connect it to the MapView.
  2. Set the map's LoadSettings.featureTilingMode to enabledWithFullResolutionWhenSupported.
  3. Create a GeometryEditor and connect it to the map view.
  4. Create a ReticleVertexTool and set it into the GeometryEditor.tool.
  5. Call syncSourceSettings after the map's operational layers are loaded and the geometry editor connected to the map view.
  6. Set SnapSettings.isEnabled and SnapSourceSettings.isEnabled to true for the SnapSource of interest.
  7. Enable or disable geometry guides using SnapSettings.isGeometryGuidesEnabled and feature snapping using SnapSettings.isFeatureSnappingEnabled.
  8. Start the geometry editor with a GeometryType.

Relevant API

  • FeatureLayer
  • Geometry
  • GeometryEditor
  • GeometryEditorReticle
  • GeometryEditorStyle
  • GraphicsOverlay
  • MapView
  • ReticleVertexTool
  • SnapSettings
  • SnapSource
  • SnapSourceSettings

About the data

The Naperville water distribution network is based on ArcGIS Solutions for Water Utilities and provides a realistic depiction of a theoretical stormwater network.

Additional information

Snapping is used to maintain data integrity between different sources of data when editing, so it is important that each SnapSource provides full resolution geometries to be valid for snapping. This means that some of the default optimizations used to improve the efficiency of data transfer and display of polygon and polyline layers based on feature services are not appropriate for use with snapping.

To snap to polygon and polyline layers, the recommended approach is to set the FeatureLayer's feature tiling mode to FeatureTilingMode.enabledWithFullResolutionWhenSupported and use the default ServiceFeatureTable feature request mode FeatureRequestMode.onInteractionCache. Local data sources, such as geodatabases, always provide full resolution geometries.

Snapping can be used during interactive edits that move existing vertices using the VertexTool or ReticleVertexTool. It is also supported for adding new vertices for input devices with a hover event (such as a mouse move without a mouse button press). Using the ReticleVertexTool to add and move vertices allows users of touch screen devices to clearly see the visual cues for snapping.

Geometry guides are enabled by default when snapping is enabled. These allow for snapping to a point coinciding with, parallel to, perpendicular to, or extending an existing geometry.

On supported platforms haptic feedback on SnapState.snappedToFeature and SnapState.snappedToGeometryGuide is enabled by default when snapping is enabled. Custom haptic feedback can be configured by setting SnapSettings.isHapticFeedbackEnabled to false and listening to GeometryEditor.snapChanged events to provide specific feedback depending on the SnapState.

When using SubtypeFeatureLayer objects as snap sources instead of FeatureLayer, child SubtypeSublayer objects are included as snap sources in the parent SnapSourceSettings.childSnapSources collection in the same order as the SubtypeFeatureLayer.subtypeSublayers collection.

This sample uses the GeoView-Compose Toolkit module to be able to implement a composable MapView.

Tags

edit, feature, geometryeditor, geoview-compose, graphics, layers, magnify, map, reticle, snapping

Sample Code

MapViewModel.ktMapViewModel.ktMainActivity.ktMainScreen.ktSnapSettingsScreen.ktButtonMenu.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
/* Copyright 2024 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.snapgeometryedits.components

import android.app.Application
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.unit.dp
import androidx.lifecycle.AndroidViewModel
import com.arcgismaps.geometry.GeometryType
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.layers.FeatureTilingMode
import com.arcgismaps.mapping.view.Graphic
import com.arcgismaps.mapping.view.GraphicsOverlay
import com.arcgismaps.mapping.view.SingleTapConfirmedEvent
import com.arcgismaps.mapping.view.geometryeditor.GeometryEditor
import com.arcgismaps.mapping.view.geometryeditor.GeometryEditorStyle
import com.arcgismaps.mapping.view.geometryeditor.ReticleVertexTool
import com.arcgismaps.mapping.view.geometryeditor.SnapSourceSettings
import com.arcgismaps.toolkit.geoviewcompose.MapViewProxy
import com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModel
import com.esri.arcgismaps.sample.snapgeometryedits.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class MapViewModel(
    application: Application,
    private val sampleCoroutineScope: CoroutineScope
) : AndroidViewModel(application) {
    // create a map using the URL of the web map
    val map = ArcGISMap(application.getString(R.string.web_map))

    // create a graphic, graphic overlay, and geometry editorenc
    private var identifiedGraphic = Graphic()
    val graphicsOverlay = GraphicsOverlay()
    val geometryEditor = GeometryEditor()

    // create a mapViewProxy that will be used to identify features in the MapView and set the viewpoint
    val mapViewProxy = MapViewProxy()

    // create a messageDialogViewModel to handle dialog interactions
    val messageDialogVM: MessageDialogViewModel = MessageDialogViewModel()

    // create lists for displaying the snap sources in the bottom sheet
    private val _snapSourceSettingsList = MutableStateFlow(listOf<SnapSourceSettings>())
    val snapSourceList: StateFlow<List<SnapSourceSettings>> = _snapSourceSettingsList

    // create boolean flags to track the state of UI components
    val isCreateButtonEnabled = mutableStateOf(false)
    val isSnapSettingsButtonEnabled = mutableStateOf(false)
    val isBottomSheetVisible = mutableStateOf(false)
    val snappingCheckedState = mutableStateOf(geometryEditor.snapSettings.isEnabled)
    val geometryGuidesCheckedState = mutableStateOf(geometryEditor.snapSettings.isGeometryGuidesEnabled)
    val featureSnappingCheckedState = mutableStateOf(geometryEditor.snapSettings.isFeatureSnappingEnabled)
    val snapSourceCheckedState = mutableStateListOf<Boolean>()
    val isUndoButtonEnabled = geometryEditor.canUndo
    val isSaveButtonEnabled = geometryEditor.isStarted
    val isDeleteButtonEnabled = geometryEditor.isStarted

    /**
     * Configure the map and enable the UI after the map's layers are loaded.
     */
    init {
        // set the id for the graphics overlay
        graphicsOverlay.id = "Editor Graphics Overlay"
        // set the tool for the geometry editor to use a reticle
        geometryEditor.tool = ReticleVertexTool()
        // set the feature layer's tiling mode
        map.loadSettings.featureTilingMode =
            FeatureTilingMode.EnabledWithFullResolutionWhenSupported

        isCreateButtonEnabled.value = true
        isSnapSettingsButtonEnabled.value = true

        sampleCoroutineScope.launch {
            // load the map
            map.load().onSuccess {
                // load the map's operational layers
                map.operationalLayers.forEach { layer ->
                    layer.load().onFailure { error ->
                        messageDialogVM.showMessageDialog(
                            error.message.toString(),
                            error.cause.toString()
                        )
                    }
                }
            }.onFailure { error ->
                messageDialogVM.showMessageDialog(
                    error.message.toString(),
                    error.cause.toString()
                )
            }
        }
    }

    /**
     * Synchronises the snap source collection with the map's operational layers, sets the bottom
     * sheet UI, and shows it to configure snapping.
     */
    fun showBottomSheet() {
        if (geometryEditor.snapSettings.sourceSettings.isEmpty()) {
            // sync the snap source collection
            geometryEditor.snapSettings.syncSourceSettings()
            // initialise the snap source lists used for the bottom sheet
            geometryEditor.snapSettings.sourceSettings.forEach { snapSource ->
                snapSourceCheckedState.add(snapSource.isEnabled)
            }
            _snapSourceSettingsList.value = geometryEditor.snapSettings.sourceSettings
        }
        isBottomSheetVisible.value = true
    }

    /**
     * Toggles snapping overall (both geometry guides and feature snapping) using the
     * [checkedValue] from the bottom sheet.
     */
    fun snappingEnabledStatus(checkedValue: Boolean) {
        snappingCheckedState.value = checkedValue
        geometryEditor.snapSettings.isEnabled = snappingCheckedState.value
    }

    /**
     * Toggles geometry guides using the [checkedValue] from the bottom sheet.
     * Note geometry guides will still be disabled unless snapping is also enabled overall.
     */
    fun geometryGuidesEnabledStatus(checkedValue: Boolean) {
        geometryGuidesCheckedState.value = checkedValue
        geometryEditor.snapSettings.isGeometryGuidesEnabled = geometryGuidesCheckedState.value
    }

    /**
     * Toggles feature snapping using the [checkedValue] from the bottom sheet.
     * Note feature snapping will still be disabled unless snapping is also enabled overall.
     */
    fun featureSnappingEnabledStatus(checkedValue: Boolean) {
        featureSnappingCheckedState.value = checkedValue
        geometryEditor.snapSettings.isFeatureSnappingEnabled = featureSnappingCheckedState.value
    }

    /**
     * Toggles snapping for the snap source at [index] using the [checkedValue] from the
     * BottomSheet.
     */
    fun sourceEnabledStatus(checkedValue: Boolean, index: Int) {
        snapSourceCheckedState[index] = checkedValue
        geometryEditor.snapSettings.sourceSettings[index].isEnabled = snapSourceCheckedState[index]
    }

    /**
     * Hides the bottom sheet.
     */
    fun dismissBottomSheet() {
        isBottomSheetVisible.value = false
    }

    /**
     * Starts the GeometryEditor using the selected [GeometryType].
     */
    fun startEditor(selectedGeometry: GeometryType) {
        if (!geometryEditor.isStarted.value) {
            geometryEditor.start(selectedGeometry)
            isCreateButtonEnabled.value = false
        }
    }

    /**
     * Stops the GeometryEditor and updates the identified graphic or calls [createGraphic].
     */
    fun stopEditor() {
        if (identifiedGraphic.geometry != null) {
            identifiedGraphic.geometry = geometryEditor.stop()
            identifiedGraphic.isSelected = false
        } else if (geometryEditor.isStarted.value) {
            createGraphic()
        }
        isCreateButtonEnabled.value = true
    }

    /**
     * Creates a graphic from the geometry and add it to the GraphicsOverlay.
     */
    private fun createGraphic() {
        val geometry = geometryEditor.stop()
            ?: return messageDialogVM.showMessageDialog(
                "Error!",
                "Error stopping editing session"
            )
        val graphic = Graphic(geometry)

        when (geometry) {
            is Point, is Multipoint -> graphic.symbol = GeometryEditorStyle().vertexSymbol
            is Polyline -> graphic.symbol = GeometryEditorStyle().lineSymbol
            is Polygon -> graphic.symbol = GeometryEditorStyle().fillSymbol
            else -> {}
        }
        graphicsOverlay.graphics.add(graphic)
        graphic.isSelected = false
    }

    /**
     * Deletes the selected element and stops the geometry editor if there are no
     * more elements in the geometry.
     */
    fun deleteSelection() {
        if (geometryEditor.geometry.value?.isEmpty == true) {
            geometryEditor.stop()
            isCreateButtonEnabled.value = true
        }

        val selectedElement = geometryEditor.selectedElement.value
        if (selectedElement?.canDelete == true) {
            geometryEditor.deleteSelectedElement()
        }
    }

    /**
     * Reverts the last event on the geometry editor.
     */
    fun editorUndo() {
        geometryEditor.undo()
    }

    /**
     * Identifies the graphic at the tapped screen coordinate in the provided [singleTapConfirmedEvent]
     * and starts the GeometryEditor using the identified graphic's geometry. Hide the BottomSheet on
     * [singleTapConfirmedEvent].
     */
    fun identify(singleTapConfirmedEvent: SingleTapConfirmedEvent) {
        sampleCoroutineScope.launch {
            val graphicsResult = mapViewProxy.identifyGraphicsOverlays(
                screenCoordinate = singleTapConfirmedEvent.screenCoordinate,
                tolerance = 10.0.dp,
                returnPopupsOnly = false
            ).getOrNull()

            if (!geometryEditor.isStarted.value) {
                if (graphicsResult != null) {
                    if (graphicsResult.isNotEmpty()) {
                        identifiedGraphic = graphicsResult[0].graphics[0]
                        identifiedGraphic.isSelected = true
                        identifiedGraphic.geometry?.let {
                            geometryEditor.start(it)
                            isCreateButtonEnabled.value = false
                        }
                    }
                }
                identifiedGraphic.geometry = null
            }
        }
        dismissBottomSheet()
    }
}

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