Snap geometry edits

View inMAUIUWPWPFWinUIView 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 mouse pointer or drag a vertex to nearby an existing feature or graphic. When the pointer is close to that existing geoelement, the edit position will be adjusted to coincide with (or snap to), edges and vertices of its geometry. Click or release the touch pointer to place the vertex at the snapped location.

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

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

To delete a geometry or a vertex, tap the geometry or vertex to select it 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. Call SyncSourceSettings after the map's operational layers are loaded and the geometry editor has connected to the map view.
  5. Set SnapSettings.IsEnabled and SnapSourceSettings.IsEnabled to true for the SnapSource of interest.
  6. Toggle geometry guides using SnapSettings.IsGeometryGuidesEnabled and feature snapping using SnapSettings.IsFeatureSnappingEnabled.
  7. Start the geometry editor with a GeometryType.

Relevant API

  • FeatureLayer
  • Geometry
  • GeometryEditor
  • GeometryEditorStyle
  • GraphicsOverlay
  • MapView
  • 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. Point and multipoint feature layers are also always full resolution.

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.

Tags

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

Sample Code

SnapGeometryEdits.xaml.csSnapGeometryEdits.xaml.csSnapGeometryEdits.xaml
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
// 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.

using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using Esri.ArcGISRuntime.UI.Editing;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;

namespace ArcGIS.WPF.Samples.SnapGeometryEdits
{
    [ArcGIS.Samples.Shared.Attributes.Sample(
        name: "Snap geometry edits",
        category: "Geometry",
        description: "Use the Geometry Editor to edit a geometry and align it to existing geometries on a map.",
        instructions: "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.",
        tags: new[] { "edit", "feature", "geometry editor", "graphics", "layers", "map", "snapping" })]
    public partial class SnapGeometryEdits
    {
        // Hold references for use in event handlers.
        private GeometryEditor _geometryEditor;
        private GraphicsOverlay _graphicsOverlay;
        private Graphic _selectedGraphic;
        private List<ToggleButton> _geometryEditorToolButtons;

        public SnapGeometryEdits()
        {
            InitializeComponent();
            _ = Initialize();
        }

        private async Task Initialize()
        {
            // Create a map using a Uri.
            var myMap = new Map(new Uri("https://www.arcgis.com/home/item.html?id=b95fe18073bc4f7788f0375af2bb445e"));

            // Set the map load setting feature tiling mode.
            // Enabled with full resolution when supported is used to ensure that snapping to geometries occurs in full resolution.
            // Snapping in full resolution improves snapping accuracy.
            myMap.LoadSettings.FeatureTilingMode = FeatureTilingMode.EnabledWithFullResolutionWhenSupported;

            // Set the initial viewpoint.
            myMap.InitialViewpoint = new Viewpoint(new MapPoint(-9812798, 5126406, SpatialReferences.WebMercator), 2000);

            // Create a graphics overlay and add it to the map view.
            _graphicsOverlay = new GraphicsOverlay();
            MyMapView.GraphicsOverlays.Add(_graphicsOverlay);

            // Add the map to the map view.
            MyMapView.Map = myMap;

            // Create and add a geometry editor to the map view.
            _geometryEditor = new GeometryEditor();
            MyMapView.GeometryEditor = _geometryEditor;

            // Load the map.
            await myMap.LoadAsync();

            // Ensure all layers are loaded before setting the snap settings.
            // If this is not awaited there is a risk that operational layers may not have loaded and therefore would not have been included in the snap sources.
            await Task.WhenAll(MyMapView.Map.OperationalLayers.ToList().Select(layer => layer.LoadAsync()).ToList());

            // Set the snap source settings.
            SetSnapSettings();

            // Show the UI.
            SnappingControls.Visibility = Visibility.Visible;

            // Store a reference to the geometry editor tool buttons to update their background color when selected.
            _geometryEditorToolButtons = new List<ToggleButton>()
            {
                PointButton,
                PolylineButton,
                PolygonButton,
                MultipointButton
            };

            // Add an event handler to detect geoview tapped events.
            MyMapView.GeoViewTapped += MyMapView_GeoViewTapped;
        }

        private void SetSnapSettings()
        {
            // Synchronize the snap source collection with the map's operational layers.
            // Note that layers that have not been loaded will not synchronize.
            _geometryEditor.SnapSettings.SyncSourceSettings();

            // Enable snapping on the geometry layer.
            _geometryEditor.SnapSettings.IsEnabled = true;

            // Create a list of snap source settings with snapping disabled.
            List<SnapSourceSettingsVM> snapSourceSettingsVMs = _geometryEditor.SnapSettings.SourceSettings.Select(sourceSettings => new SnapSourceSettingsVM(sourceSettings) { IsEnabled = false }).ToList();

            // Populate lists of snap source settings for point and polyline layers.
            PointSnapSettingsList.ItemsSource = snapSourceSettingsVMs.Where(snapSourceSettingVM => snapSourceSettingVM.GeometryType == GeometryType.Point).ToList();
            PolylineSnapSettingsList.ItemsSource = snapSourceSettingsVMs.Where(snapSourceSettingVM => snapSourceSettingVM.GeometryType == GeometryType.Polyline).ToList();

            // Populate a list of snap source settings for graphics overlays.
            GraphicsOverlaySnapSettingsList.ItemsSource = snapSourceSettingsVMs.Where(snapSourceSettingsVM => snapSourceSettingsVM.SnapSourceSettings.Source is GraphicsOverlay).ToList();
        }

        private void CreateNewGraphic()
        {
            // Get the new geometry from the geometry editor.
            Geometry geometry = _geometryEditor.Stop();

            // Create a graphic.
            var graphic = new Graphic(geometry);

            // Create a geometry editor style to get symbols for the new graphic.
            var geometryEditorStyle = new GeometryEditorStyle();

            switch (geometry.GeometryType)
            {
                case GeometryType.Point:
                    graphic.Symbol = geometryEditorStyle.VertexSymbol;
                    break;
                case GeometryType.Envelope:
                    graphic.Symbol = geometryEditorStyle.LineSymbol;
                    break;
                case GeometryType.Polyline:
                    graphic.Symbol = geometryEditorStyle.LineSymbol;
                    break;
                case GeometryType.Polygon:
                    graphic.Symbol = geometryEditorStyle.FillSymbol;
                    break;
                case GeometryType.Multipoint:
                    graphic.Symbol = geometryEditorStyle.VertexSymbol;
                    break;
            }

            // Add the graphic to the GraphicsOverlay and unselect it.
            _graphicsOverlay.Graphics.Add(graphic);
            graphic.IsSelected = false;
        }

        private async void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e)
        {
            // If the geometry editor is active then stop.
            if (_geometryEditor.IsStarted) return;

            try
            {
                // Get the list of identified graphics overlay results based on tap position.
                IReadOnlyList<IdentifyGraphicsOverlayResult> results = await MyMapView.IdentifyGraphicsOverlaysAsync(e.Position, 10, false);

                // If a graphics overlay result has been tapped and contains a corresponding graphic,
                // set the selected graphic and start the geometry editor.
                if (results.Any() && results[0].Graphics.Any())
                {
                    _selectedGraphic = results[0].Graphics[0];
                    _selectedGraphic.IsSelected = true;
                }
                else
                {
                    // No results have been found, update the selected graphic.
                    _selectedGraphic = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

                // Reset the UI.
                ResetFromEditingSession();
                return;
            }

            if (_selectedGraphic == null) return;

            // Hide the selected graphic and start an editing session with a copy of it.
            _geometryEditor.Start(_selectedGraphic.Geometry);
            _selectedGraphic.IsVisible = false;
        }

        // Reset the UI after the editor stops.
        private void ResetFromEditingSession()
        {
            // Reset the selected graphic.
            if (_selectedGraphic != null)
            {
                _selectedGraphic.IsSelected = false;
                _selectedGraphic.IsVisible = true;
            }

            foreach (var toggleButton in _geometryEditorToolButtons)
            {
                toggleButton.IsChecked = false;
            }

            _selectedGraphic = null;
        }

        #region Enable Snapping Button Handlers
        // Enable all snap settings.
        private void EnableAllSnapSettingsButton_Click(object sender, RoutedEventArgs e)
        {
            _geometryEditor.SnapSettings.IsEnabled = true;
            _geometryEditor.SnapSettings.IsGeometryGuidesEnabled = true;
            _geometryEditor.SnapSettings.IsFeatureSnappingEnabled = true;
        }

        // Enable all point layer snap sources.
        private void EnableAllPointSnapSourceButton_Click(object sender, RoutedEventArgs e)
        {
            foreach (var item in PointSnapSettingsList.ItemsSource)
            {
                if (item is SnapSourceSettingsVM snapSourceSettingsVM)
                {
                    snapSourceSettingsVM.IsEnabled = true;
                }
            }
        }

        // Enable all polyline layer snap sources.
        private void EnableAllPolylineSnapSourceButton_Click(object sender, RoutedEventArgs e)
        {
            foreach (var item in PolylineSnapSettingsList.ItemsSource)
            {
                if (item is SnapSourceSettingsVM snapSourceSettingsVM)
                {
                    snapSourceSettingsVM.IsEnabled = true;
                }
            }
        }
        #endregion

        #region Geometry Management Button Handlers
        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            _geometryEditor.DeleteSelectedElement();
        }

        private void UndoButton_Click(object sender, RoutedEventArgs e)
        {
            _geometryEditor.Undo();
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            if (_selectedGraphic?.Geometry != null)
            {
                _selectedGraphic.Geometry = _geometryEditor.Stop();
                _selectedGraphic.IsSelected = false;
            }
            else if (_geometryEditor.IsStarted)
            {
                CreateNewGraphic();
            }

            ResetFromEditingSession();
        }

        private void DiscardButton_Click(object sender, RoutedEventArgs e)
        {
            _geometryEditor.Stop();

            ResetFromEditingSession();
        }
        #endregion

        #region Geometry Tool Buttons Handlers
        private void ReticleVertexToolCheckBox_CheckedChanged(object sender, RoutedEventArgs e)
        {
            if (ReticleVertexToolCheckBox.IsChecked == true)
            {
                _geometryEditor.Tool = new ReticleVertexTool();
            }
            else
            {
                _geometryEditor.Tool = new VertexTool();
            }
        }

        private void PointButton_Click(object sender, RoutedEventArgs e)
        {
            if (_geometryEditor.IsStarted)
            {
                _geometryEditor.Stop();
            }

            ResetFromEditingSession();

            PointButton.IsChecked = true;
            _geometryEditor.Start(GeometryType.Point);
        }

        private void MultipointButton_Click(object sender, RoutedEventArgs e)
        {
            if (_geometryEditor.IsStarted)
            {
                _geometryEditor.Stop();
            }

            ResetFromEditingSession();

            MultipointButton.IsChecked = true;
            _geometryEditor.Start(GeometryType.Multipoint);
        }
        private void PolylineButton_Click(object sender, RoutedEventArgs e)
        {
            if (_geometryEditor.IsStarted)
            {
                _geometryEditor.Stop();
            }

            ResetFromEditingSession();

            PolylineButton.IsChecked = true;
            _geometryEditor.Start(GeometryType.Polyline);
        }
        private void PolygonButton_Click(object sender, RoutedEventArgs e)
        {
            if (_geometryEditor.IsStarted)
            {
                _geometryEditor.Stop();
            }

            ResetFromEditingSession();

            PolygonButton.IsChecked = true;
            _geometryEditor.Start(GeometryType.Polygon);
        }
        #endregion
    }

    public class SnapSourceSettingsVM : INotifyPropertyChanged
    {
        public SnapSourceSettings SnapSourceSettings { get; set; }

        // Wrap the snap source settings in a view model to expose them to the UI.
        public SnapSourceSettingsVM(SnapSourceSettings snapSourceSettings)
        {
            SnapSourceSettings = snapSourceSettings;

            if (snapSourceSettings.Source is FeatureLayer featureLayer)
            {
                Name = featureLayer.Name;

                if (featureLayer.FeatureTable != null)
                {
                    GeometryType = featureLayer.FeatureTable.GeometryType;
                }
            }
            else if (snapSourceSettings.Source is GraphicsOverlay)
            {
                Name = "Editor graphics overlay";
            }

            IsEnabled = snapSourceSettings.IsEnabled;
        }

        private string _name;
        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
                OnPropertyChanged();
            }
        }

        private bool _isEnabled;
        public bool IsEnabled
        {
            get
            {
                return _isEnabled;
            }
            set
            {
                _isEnabled = value;
                SnapSourceSettings.IsEnabled = value;
                OnPropertyChanged();
            }
        }

        public GeometryType GeometryType { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

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