Edit and sync features

View inC++QMLView on GitHubSample viewer app

Synchronize offline edits with a feature service.

screenshot

Use case

A survey worker who works in an area without an internet connection could take a geodatabase of survey features offline at their office, make edits and add new features to the offline geodatabase in the field, and sync the updates with the online feature service after returning to the office.

How to use the sample

Pan and zoom to position the red rectangle around the area you want to take offline. Click "Generate geodatabase" to take the area offline. When complete, the map will update to only show the offline area. To edit features, click to select a feature, and click again anywhere else on the map to move the selected feature to the clicked location. To sync the edits with the feature service, click the "Sync geodatabase" button.

How it works

  1. Create a GeodatabaseSyncTask from a URL to a feature service.
  2. Create GenerateGeodatabaseParameters, passing in an Envelope extent as the parameter.
  3. Create a GenerateGeodatabaseJob from the GeodatabaseSyncTask using generateGeodatabase(...), passing in the parameters and a path to where the geodatabase should be downloaded locally.
  4. Start the job and get the result Geodatabase.
  5. Load the geodatabase and get its feature tables. Create feature layers from the feature tables and add them to the map's operational layers collection.
  6. Create SyncGeodatabaseParameters and set the sync direction.
  7. Create a SyncGeodatabaseJob from GeodatabaseSyncTask using syncGeodatabase(...) passing in the parameters and geodatabase as arguments.
  8. Start the sync job to synchronize the edits.

Relevant API

  • FeatureLayer
  • FeatureTable
  • GenerateGeodatabaseJob
  • GenerateGeodatabaseParameters
  • GeodatabaseSyncTask
  • SyncGeodatabaseJob
  • SyncGeodatabaseParameters
  • SyncLayerOption

Offline Data

To set up the sample's offline data, see the Use offline data in the samples section of the Qt Samples repository overview.

Link Local Location
San Francisco Streets TPKX <userhome>/ArcGIS/Runtime/Data/tpkx/SanFrancisco.tpkx

About the data

The basemap uses an offline tile package of San Francisco. The online feature service has features with wildfire information.

Tags

feature service, geodatabase, offline, synchronize

Sample Code

EditAndSyncFeatures.cppEditAndSyncFeatures.cppEditAndSyncFeatures.hEditAndSyncFeatures.qml
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
// [WriteFile Name=EditAndSyncFeatures, Category=EditData]
// [Legal]
// Copyright 2016 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.
// [Legal]

#ifdef PCH_BUILD
#include "pch.hpp"
#endif // PCH_BUILD

#include "EditAndSyncFeatures.h"

#include "Map.h"
#include "MapQuickView.h"
#include "TileCache.h"
#include "ArcGISTiledLayer.h"
#include "Basemap.h"
#include "Viewpoint.h"
#include "Envelope.h"
#include "GenerateGeodatabaseParameters.h"
#include "ServiceFeatureTable.h"
#include "FeatureLayer.h"
#include "GeodatabaseSyncTask.h"
#include "GeodatabaseFeatureTable.h"
#include "GeometryEngine.h"
#include "Geodatabase.h"
#include "Point.h"

#include <QUrl>
#include <QDir>
#include <QtCore/qglobal.h>

#ifdef Q_OS_IOS
#include <QStandardPaths>
#endif // Q_OS_IOS

using namespace Esri::ArcGISRuntime;

// helper method to get cross platform data path
namespace
{
  QString defaultDataPath()
  {
    QString dataPath;

  #ifdef Q_OS_ANDROID
    dataPath = "/sdcard";
  #elif defined Q_OS_IOS
    dataPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
  #else
    dataPath = QDir::homePath();
  #endif

    return dataPath;
  }
} // namespace

EditAndSyncFeatures::EditAndSyncFeatures(QQuickItem* parent /* = nullptr */):
  QQuickItem(parent),
  m_dataPath(defaultDataPath() + "/ArcGIS/Runtime/Data/")
{
}

EditAndSyncFeatures::~EditAndSyncFeatures()
{
  // unregister geodatabase
  m_syncTask->unregisterGeodatabase(m_offlineGdb);
}

void EditAndSyncFeatures::init()
{
  qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
  qmlRegisterType<EditAndSyncFeatures>("Esri.Samples", 1, 0, "EditAndSyncFeaturesSample");
}

void EditAndSyncFeatures::componentComplete()
{
  QQuickItem::componentComplete();

  // find QML MapView component
  m_mapView = findChild<MapQuickView*>("mapView");
  m_mapView->setWrapAroundMode(WrapAroundMode::Disabled);

  // Create a map using a local tile package
  TileCache* tileCache = new TileCache(m_dataPath + "tpkx/SanFrancisco.tpkx", this);
  ArcGISTiledLayer* tiledLayer = new ArcGISTiledLayer(tileCache, this);
  Basemap* basemap = new Basemap(tiledLayer, this);
  m_map = new Map(basemap, this);

  // add a feature service to the map
  ServiceFeatureTable* featureTable = new ServiceFeatureTable(QUrl(m_featureServiceUrl + QString::number(m_featureLayerId)), this);
  FeatureLayer* featureLayer = new FeatureLayer(featureTable, this);
  m_map->operationalLayers()->append(featureLayer);

  // set an initial viewpoint
  Envelope env(-122.50017, 37.74500, -122.43843, 37.81638, SpatialReference(4326));
  Viewpoint viewpoint(env);
  m_map->setInitialViewpoint(viewpoint);

  // Set map to map view
  m_mapView->setMap(m_map);

  // create the GeodatabaseSyncTask
  m_syncTask = new GeodatabaseSyncTask(QUrl(m_featureServiceUrl), this);

  connectSignals();
}

void EditAndSyncFeatures::connectSignals()
{
  // lambda expression for the mouse clicked signal on the mapview
  connect(m_mapView, &MapQuickView::mouseClicked, this, [this](QMouseEvent& mouseEvent)
  {
    if (m_isOffline)
    {
      if (!m_selectedFeature)
      {
        m_mapView->identifyLayer(m_map->operationalLayers()->first(), mouseEvent.x(), mouseEvent.y(), 5, false, 1);
      }
      else
      {
        // connect to feature table signal
        FeatureLayer* featureLayer = static_cast<FeatureLayer*>(m_map->operationalLayers()->at(0));
        connect(featureLayer->featureTable(), &GeodatabaseFeatureTable::updateFeatureCompleted, this, [this, featureLayer](QUuid, bool success)
        {
          if (success)
          {
            featureLayer->clearSelection();
            m_selectedFeature = nullptr;
            emit updateInstruction("Tap the sync button");
            emit showButton();
          }
        });

        // get the point from the mouse point
        Point mapPoint = m_mapView->screenToLocation(mouseEvent.x(), mouseEvent.y());
        m_selectedFeature->setGeometry(mapPoint);
        featureLayer->featureTable()->updateFeature(m_selectedFeature);
      }
    }
  });

  // once the identify is done
  connect(m_mapView, &MapQuickView::identifyLayerCompleted, this, [this](QUuid, Esri::ArcGISRuntime::IdentifyLayerResult* identifyResult)
  {
    if (!identifyResult)
      return;

    // clear any existing selection
    FeatureLayer* featureLayer = static_cast<FeatureLayer*>(m_map->operationalLayers()->first());
    featureLayer->clearSelection();
    m_selectedFeature = nullptr;

    if (identifyResult->geoElements().length() > 0)
    {
      GeoElement* geoElement = identifyResult->geoElements().at(0);
      m_selectedFeature = static_cast<ArcGISFeature*>(geoElement);
      featureLayer->selectFeature(m_selectedFeature);
      emit updateInstruction("Tap on map to move feature");
    }
  });
}

//! [EditAndSyncFeatures parameters generate]
GenerateGeodatabaseParameters EditAndSyncFeatures::getGenerateParameters(Envelope gdbExtent)
{
  // create the parameters
  GenerateGeodatabaseParameters params;
  params.setReturnAttachments(false);
  params.setOutSpatialReference(SpatialReference::webMercator());
  params.setExtent(gdbExtent);

  // set the layer options for 1 layer
  QList<GenerateLayerOption> layerOptions;
  GenerateLayerOption generateLayerOption(m_featureLayerId);
  layerOptions << generateLayerOption;
  params.setLayerOptions(layerOptions);

  return params;
}
//! [EditAndSyncFeatures parameters generate]

//! [EditAndSyncFeatures parameters sync]
SyncGeodatabaseParameters EditAndSyncFeatures::getSyncParameters()
{
  // create the parameters
  SyncGeodatabaseParameters params;
  params.setGeodatabaseSyncDirection(SyncDirection::Bidirectional);

  // set the layer options for 1 layer
  QList<SyncLayerOption> layerOptions;
  SyncLayerOption syncLayerOption(m_featureLayerId);
  layerOptions << syncLayerOption;
  params.setLayerOptions(layerOptions);

  return params;
}
//! [EditAndSyncFeatures parameters sync]

//! [EditAndSyncFeatures generate]
void EditAndSyncFeatures::generateGeodatabaseFromCorners(double xCorner1, double yCorner1, double xCorner2, double yCorner2)
{
  // create an envelope from the QML rectangle corners
  const Point corner1 = m_mapView->screenToLocation(xCorner1, yCorner1);
  const Point corner2 = m_mapView->screenToLocation(xCorner2, yCorner2);
  const Envelope extent(corner1, corner2);
  const Geometry geodatabaseExtent = GeometryEngine::project(extent, SpatialReference::webMercator());

  // get the updated parameters
  GenerateGeodatabaseParameters params = getGenerateParameters(geodatabaseExtent);

  // execute the task and obtain the job
  const QString outputGdb = m_temporaryDir.path() + "/Wildfire.geodatabase";
  GenerateGeodatabaseJob* generateJob = m_syncTask->generateGeodatabase(params, outputGdb);

  // connect to the job's status changed signal
  if (generateJob)
  {
    connect(generateJob, &GenerateGeodatabaseJob::statusChanged, this, [this, generateJob](JobStatus jobStatus)
    {
      // connect to the job's status changed signal to know once it is done
      switch (jobStatus) {
      case JobStatus::Failed:
        emit updateStatus("Generate failed");
        emit hideWindow(5000, false);
        break;
      case JobStatus::NotStarted:
        emit updateStatus("Job not started");
        break;
      case JobStatus::Paused:
        emit updateStatus("Job paused");
        break;
      case JobStatus::Started:
        emit updateStatus("In progress...");
        break;
      case JobStatus::Succeeded:
        m_isOffline = true;
        m_offlineGdb = generateJob->result();
        emit isOfflineChanged();
        emit updateStatus("Complete");
        emit hideWindow(1500, true);
        emit updateInstruction("Tap on a feature");
        addOfflineData();
        break;
      default:
        break;
      }
    });

    // start the generate job
    generateJob->start();
  }
  //! [EditAndSyncFeatures generate]
  else
  {
    emit updateStatus("Generate failed");
    emit hideWindow(5000, false);
  }
}

void EditAndSyncFeatures::addOfflineData()
{
  // remove the original online feature layers
  m_map->operationalLayers()->clear();

  // load the geodatabase
  connect(m_offlineGdb, &Geodatabase::doneLoading, this, [this](Error)
  {
    // create a feature layer from each feature table, and add to the map
    const auto tables = m_offlineGdb->geodatabaseFeatureTables();
    for (GeodatabaseFeatureTable* featureTable : tables)
    {
      FeatureLayer* featureLayer = new FeatureLayer(featureTable, this);
      m_map->operationalLayers()->append(featureLayer);
    }
  });
  m_offlineGdb->load();
}

bool EditAndSyncFeatures::isOffline() const
{
  return m_isOffline;
}

//! [EditAndSyncFeatures executeSync]
void EditAndSyncFeatures::executeSync()
{
  // get the updated parameters
  SyncGeodatabaseParameters params = getSyncParameters();

  // execute the task and obtain the job
  SyncGeodatabaseJob* syncJob = m_syncTask->syncGeodatabase(params, m_offlineGdb);

  // connect to the job's status changed signal
  if (syncJob)
  {
    connect(syncJob, &GenerateGeodatabaseJob::statusChanged, this, [this](JobStatus jobStatus)
    {
      // connect to the job's status changed signal to know once it is done
      switch (jobStatus) {
      case JobStatus::Failed:
        emit updateStatus("Sync failed");
        emit hideWindow(5000, false);
        break;
      case JobStatus::NotStarted:
        emit updateStatus("Job not started");
        break;
      case JobStatus::Paused:
        emit updateStatus("Job paused");
        break;
      case JobStatus::Started:
        emit updateStatus("In progress...");
        break;
      case JobStatus::Succeeded:
        m_isOffline = true;
        emit isOfflineChanged();
        emit updateStatus("Complete");
        emit hideWindow(1500, true);
        emit updateInstruction("Tap on a feature");
        break;
      default:
        break;
      }
    });

    // start the sync job
    syncJob->start();
  }
  //! [EditAndSyncFeatures executeSync]
  else
  {
    emit updateStatus("Sync failed");
    emit hideWindow(5000, false);
  }
}

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