Manage features

View inMAUIWinUIWPFView on GitHub

Create, update, and delete features to manage a feature layer.

Image of manage features

Use case

An end-user performing a survey may want to manage features on the map in various ways during the course of their work.

How to use the sample

Pick an operation, then tap on the map to perform the operation at that location. Available feature management operations include: "Create feature", "Delete feature", "Update attribute", and "Update geometry".

How it works

  1. Create a ServiceGeodatabase from a URL.
  2. Get a ServiceFeatureTable from the ServiceGeodatabase.
  3. Create a FeatureLayer derived from the ServiceFeatureTable instance.
  4. Update the GeoViewTappedEvent subscription when a feature management operation is selected.
  5. Apply the feature management operation upon tapping the map.
    • Create features: create a Feature with attributes and a location using the ServiceFeatureTable.
    • Delete features: delete the selected Feature from the FeatureTable.
    • Update attribute: update the attribute of the selected Feature.
    • Update geometry: update the geometry of the selected Feature.
  6. Update the FeatureTable locally.
  7. Update the ServiceGeodatabase of the ServiceFeatureTable by calling ApplyEditsAsync().
    • This pushes the changes to the server.

Relevant API

  • Feature
  • FeatureEditResult
  • FeatureLayer
  • ServiceFeatureTable
  • ServiceGeodatabase

Additional information

When editing feature tables that are subject to database behavior (operations on one table affecting another table), it's now recommended to call these methods (apply or undo edits) on the ServiceGeodatabase object rather than on the ServiceFeatureTable object. Using the ServiceGeodatabase object to call these operations will prevent possible data inconsistencies and ensure transactional integrity so that all changes can be committed or rolled back.

Tags

amend, attribute, create, delete, deletion, details, edit, editing, feature, feature layer, feature table, geodatabase, information, moving, online service, service, update, updating, value

Sample Code

ManageFeatures.xaml.csManageFeatures.xaml.csManageFeatures.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
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
// Copyright 2023 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.Controls;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;

namespace ArcGIS.WinUI.Samples.ManageFeatures
{
    [ArcGIS.Samples.Shared.Attributes.Sample(
        name: "Manage features",
        category: "Data",
        description: "Create, update, and delete features to manage a feature layer.",
        instructions: "Pick an operation, then tap on the map to perform the operation at that location. Available feature management operations include: \"Create feature\", \"Delete feature\", \"Update attribute\", and \"Update geometry\".",
        tags: new[] { "amend", "attribute", "create", "delete", "deletion", "details", "edit", "editing", "feature", "feature layer", "feature table", "geodatabase", "information", "moving", "online service", "service", "update", "updating", "value" })]
    [ArcGIS.Samples.Shared.Attributes.OfflineData()]
    public partial class ManageFeatures
    {
        // URL to the feature service.
        private const string FeatureServiceUrl = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0";

        // Name of the field that will be updated.
        private const string AttributeFieldName = "typdamage";

        // Hold a reference to the feature layer.
        private FeatureLayer _damageLayer;

        // Hold a reference to the feature table.
        private ServiceFeatureTable _damageFeatureTable;

        // Hold a reference to the selected feature.
        private ArcGISFeature _selectedFeature;

        // Create a button for deleting features.
        private Button _deleteButton;

        private readonly string[] _methodList = new string[]
        {
            "Create feature",
            "Delete feature",
            "Update attribute",
            "Update geometry"
        };

        private readonly string[] _instructions = new string[]
        {
            "Tap on the map to create a new feature.",
            "Tap an existing feature to delete it.",
            "Tap an existing feature to edit its attribute.",
            "Tap an existing feature to select it, tap the map to move it to a new position."
        };

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

        public async Task Initialize()
        {
            try
            {
                // Create the map with streets basemap.
                MyMapView.Map = new Map(BasemapStyle.ArcGISStreets);

                // Create a service geodatabase from the feature service.
                var serviceGeodatabase = new ServiceGeodatabase(new Uri(FeatureServiceUrl));
                await serviceGeodatabase.LoadAsync();

                // Get the feature table from the service geodatabase referencing the Damage Assessment feature service.
                // Creating the feature table from the feature service will cause the service geodatabase to be null.
                _damageFeatureTable = serviceGeodatabase.GetTable(0);

                // Update attributes - when the table loads, use it to discover the domain of the typdamage field.
                _damageFeatureTable.Loaded += DamageTable_Loaded;

                // Create a feature layer to visualize the features in the table.
                _damageLayer = new FeatureLayer(_damageFeatureTable);

                // Add the layer to the map.
                MyMapView.Map.OperationalLayers.Add(_damageLayer);

                // Zoom to the United States.
                _ = MyMapView.SetViewpointCenterAsync(new MapPoint(-10800000, 4500000, SpatialReferences.WebMercator), 3e7);

                // Bind the list of method names to the ComboBox.
                OperationChooser.ItemsSource = _methodList;

                // Create a button for deleting the feature.
                _deleteButton = new Button
                {
                    Content = "Delete incident",
                    Padding = new Thickness(5)
                };

                // Handle button clicks.
                _deleteButton.Click += DeleteButton_Click;
            }
            catch (Exception ex)
            {
                await new MessageDialog2(ex.ToString(), "Error").ShowAsync();
            }
        }

        private async void MapView_Tapped_CreateFeature(object sender, GeoViewInputEventArgs e)
        {
            try
            {
                // Create the feature.
                var feature = (ArcGISFeature)_damageFeatureTable.CreateFeature();

                // Get the normalized geometry for the tapped location and use it as the feature's geometry.
                var tappedPoint = (MapPoint)GeometryEngine.NormalizeCentralMeridian(e.Location);
                feature.Geometry = tappedPoint;

                // Set feature attributes.
                feature.SetAttributeValue("typdamage", "Minor");
                feature.SetAttributeValue("primcause", "Earthquake");

                // Add the feature to the table.
                await _damageFeatureTable.AddFeatureAsync(feature);

                // Apply the edits to the service on the service geodatabase.
                await _damageFeatureTable.ServiceGeodatabase.ApplyEditsAsync();

                // Update the feature to get the updated objectid - a temporary ID is used before the feature is added.
                feature.Refresh();

                // Confirm feature addition.
                await new MessageDialog2($"Created feature {feature.Attributes["objectid"]}", "Success").ShowAsync();
            }
            catch (Exception ex)
            {
                await new MessageDialog2(ex.ToString(), "Error").ShowAsync();
            }
        }

        #region Delete feature

        private async void MapView_Tapped_DeleteFeature(object sender, GeoViewInputEventArgs e)
        {
            // Clear any existing selection.
            _damageLayer.ClearSelection();

            // Dismiss any existing callouts.
            MyMapView.DismissCallout();

            try
            {
                // Determine if a user tapped on a feature.
                IdentifyLayerResult identifyResult = await TrySelectFeature(e.Position);

                // Do nothing if there are no results.
                if (identifyResult == null) return;

                // Otherwise, get the ID of the first result.
                var featureId = (long)identifyResult.GeoElements[0].Attributes["objectid"];

                // Get the feature by constructing a query and running it.
                var queryParameters = new QueryParameters();
                queryParameters.ObjectIds.Add(featureId);
                FeatureQueryResult queryResult = await _damageLayer.FeatureTable.QueryFeaturesAsync(queryParameters);
                Feature tappedFeature = queryResult.First();

                // Show the deletion callout.
                _deleteButton.Tag = tappedFeature;
                MyMapView.ShowCalloutAt((MapPoint)tappedFeature.Geometry, _deleteButton);
            }
            catch (Exception ex)
            {
                await new MessageDialog2(ex.ToString(), "Error").ShowAsync();
            }
        }

        private async void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            // Dismiss the callout.
            MyMapView.DismissCallout();

            try
            {
                var featureToDelete = (Feature)_deleteButton.Tag;

                // Delete the feature.
                await _damageLayer.FeatureTable.DeleteFeatureAsync(featureToDelete);

                // Sync the change with the service on the service geodatabase.
                var serviceTable = (ServiceFeatureTable)_damageLayer.FeatureTable;
                await serviceTable.ServiceGeodatabase.ApplyEditsAsync();

                // Show a message confirming the deletion.
                await new MessageDialog2("Deleted feature with ID " + featureToDelete.Attributes["objectid"], "Success").ShowAsync();
            }
            catch (Exception ex)
            {
                await new MessageDialog2(ex.ToString(), "Error").ShowAsync();
            }
        }

        #endregion Delete feature

        #region Update attribute

        private async void MapView_Tapped_UpdateAttribute(object sender, GeoViewInputEventArgs e)
        {
            // Clear any existing selection.
            _damageLayer.ClearSelection();

            try
            {
                // Perform an identify to determine if a user tapped on a feature.
                IdentifyLayerResult identifyResult = await TrySelectFeature(e.Position);

                // Reset the instruction label and return if there are no results.
                if (identifyResult == null)
                {
                    Instructions.Text = _instructions[2];
                    DamageTypeChooser.Visibility = Visibility.Collapsed;
                    return;
                }

                // Update instruction label.
                Instructions.Text = "Select damage type:";

                // Get the current value.
                string currentAttributeValue = _selectedFeature.Attributes[AttributeFieldName].ToString();

                // Update the ComboBox selection without triggering the event.
                DamageTypeChooser.SelectionChanged -= DamageType_Changed;
                DamageTypeChooser.SelectedValue = currentAttributeValue;
                DamageTypeChooser.SelectionChanged += DamageType_Changed;

                // Enable the ComboBox.
                DamageTypeChooser.Visibility = Visibility.Visible;
            }
            catch (Exception ex)
            {
                await new MessageDialog2(ex.ToString(), "Error").ShowAsync();
            }
        }

        private async void DamageType_Changed(object sender, SelectionChangedEventArgs e)
        {
            // Skip if nothing is selected.
            if (DamageTypeChooser.SelectedIndex == -1) return;

            try
            {
                // Get the new value.
                string selectedAttributeValue = DamageTypeChooser.SelectedValue.ToString();

                // Load the feature.
                await _selectedFeature.LoadAsync();

                // Update the attribute value.
                _selectedFeature.SetAttributeValue(AttributeFieldName, selectedAttributeValue);

                // Update the table.
                await _selectedFeature.FeatureTable.UpdateFeatureAsync(_selectedFeature);

                // Update the service on the service geodatabase.
                var table = (ServiceFeatureTable)_selectedFeature.FeatureTable;
                await table.ServiceGeodatabase.ApplyEditsAsync();

                // Show just the initial instructions for update geometry.
                Instructions.Text = _instructions[2];
                DamageTypeChooser.Visibility = Visibility.Collapsed;

                await new MessageDialog2($"Edited feature {_selectedFeature.Attributes["objectid"]}", "Success").ShowAsync();
            }
            catch (Exception ex)
            {
                await new MessageDialog2(ex.ToString(), "Error").ShowAsync();
            }
            finally
            {
                // Reset the selection.
                _damageLayer.ClearSelection();
                _selectedFeature = null;
            }
        }

        #endregion Update attribute

        #region Update geometry

        private void MapView_Tapped_UpdateGeometry(object sender, GeoViewInputEventArgs e)
        {
            // Select the feature if none selected, move the feature otherwise.
            if (_selectedFeature == null)
            {
                // Select the feature.
                _ = TrySelectFeature(e.Position);
            }
            else
            {
                // Move the feature.
                _ = MoveSelectedFeature(e.Location);
            }
        }

        private async Task MoveSelectedFeature(MapPoint destinationPoint)
        {
            try
            {
                // Normalize the point - needed when the tapped location is over the international date line.
                destinationPoint = (MapPoint)GeometryEngine.NormalizeCentralMeridian(destinationPoint);

                // Load the feature.
                await _selectedFeature.LoadAsync();

                // Update the geometry of the selected feature.
                _selectedFeature.Geometry = destinationPoint;

                // Apply the edit to the feature table.
                await _selectedFeature.FeatureTable.UpdateFeatureAsync(_selectedFeature);

                // Push the update to the service with the service geodatabase.
                var serviceTable = (ServiceFeatureTable)_selectedFeature.FeatureTable;
                await serviceTable.ServiceGeodatabase.ApplyEditsAsync();
                await new MessageDialog2($"Moved feature {_selectedFeature.Attributes["objectid"]}", "Success").ShowAsync();
            }
            catch (Exception ex)
            {
                await new MessageDialog2(ex.ToString(), "Error").ShowAsync();
            }
            finally
            {
                // Reset the selection.
                _damageLayer.ClearSelection();
                _selectedFeature = null;
            }
        }

        #endregion Update geometry

        private void DamageTable_Loaded(object sender, EventArgs e)
        {
            // This code needs to work with the UI, so it needs to run on the UI thread.
            DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () =>
            {
                // Get the relevant field from the table.
                var table = (ServiceFeatureTable)sender;
                Field typeDamageField = table.Fields.First(field => field.Name == AttributeFieldName);

                // Get the domain for the field.
                var attributeDomain = (CodedValueDomain)typeDamageField.Domain;

                // Update the ComboBox with the attribute values.
                DamageTypeChooser.ItemsSource = attributeDomain.CodedValues.Select(codedValue => codedValue.Name);
            });
        }

        private void OperationChooser_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Clear all potentially hooked GeoViewTapped events.
            MyMapView.GeoViewTapped -= MapView_Tapped_CreateFeature;
            MyMapView.GeoViewTapped -= MapView_Tapped_DeleteFeature;
            MyMapView.GeoViewTapped -= MapView_Tapped_UpdateAttribute;
            MyMapView.GeoViewTapped -= MapView_Tapped_UpdateGeometry;

            // Reset UI elements.
            _damageLayer.ClearSelection();
            _selectedFeature = null;
            DamageTypeChooser.Visibility = Visibility.Collapsed;
            DamageTypeChooser.SelectedIndex = -1;
            MyMapView.DismissCallout();

            // Store the selected operation's item index.
            int index = OperationChooser.SelectedIndex;

            // Update the label with the new instruction.
            Instructions.Text = _instructions[index];

            switch (index)
            {
                case 0:
                    MyMapView.GeoViewTapped += MapView_Tapped_CreateFeature;
                    break;

                case 1:
                    MyMapView.GeoViewTapped += MapView_Tapped_DeleteFeature;
                    break;

                case 2:
                    MyMapView.GeoViewTapped += MapView_Tapped_UpdateAttribute;
                    break;

                case 3:
                    MyMapView.GeoViewTapped += MapView_Tapped_UpdateGeometry;
                    break;
            }
        }

        private async Task<IdentifyLayerResult> TrySelectFeature(Point point)
        {
            try
            {
                // Perform an identify to determine if a user tapped on a feature.
                IdentifyLayerResult identifyResult = await MyMapView.IdentifyLayerAsync(_damageLayer, point, 2, false);

                // Return null if there are no results.
                if (!identifyResult.GeoElements.Any()) return null;

                // Get the tapped feature.
                _selectedFeature = (ArcGISFeature)identifyResult.GeoElements[0];

                // Select the feature.
                _damageLayer.SelectFeature(_selectedFeature);

                return identifyResult;
            }
            catch (Exception ex)
            {
                await new MessageDialog2(ex.ToString(), "Error").ShowAsync();
                return null;
            }
        }
    }
}

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