Generate a local geodatabase from an online feature service.

Use case
Generating geodatabases is the first step toward taking a feature service offline. It allows you to save features locally for offline display.
How to use the sample
Zoom to any extent. Then click ‘Generate Geodatabse’ to generate a geodatabase of features from a feature service filtered to the current extent. A red outline will show the extent used. The job’s progress is shown while the geodatabase is generated. When complete, the map will reload with only the layers in the geodatabase, clipped to the extent.
How it works
- Create a
GeodatabaseSyncTaskwith the URL of the feature service and load it. - Create
GenerateGeodatabaseParametersspecifying the extent and whether to include attachments. - Create a
GenerateGeodatabaseJobwithgeodatabaseSyncTask::generateGeodatabase(parameters, downloadPath). Start the job withjob::start(). - When the job is done,
job::result()will return the geodatabase. Inside the geodatabase are feature tables which can be used to add feature layers to the map. - Call
syncTask::unregisterGeodatabaseAsync(geodatabase)after generation when you’re not planning on syncing changes to the service.
Relevant API
- GenerateGeodatabaseJob
- GenerateGeodatabaseParameters
- Geodatabase
- GeodatabaseSyncTask
Offline Data
Read more about how to set up the sample’s offline data here.
| Link | Local Location |
|---|---|
| San Francisco Streets TPKX | <userhome>/ArcGIS/Runtime/Data/tpkx/SanFrancisco.tpkx |
Tags
disconnected, local geodatabase, offline, replica, sync
Sample Code
// [WriteFile Name=GenerateGeodatabaseReplicaFromFeatureService, Category=Features]// [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
// sample headers#include "GenerateGeodatabaseReplicaFromFeatureService.h"
// ArcGIS Maps SDK headers#include "ArcGISFeatureServiceInfo.h"#include "ArcGISTiledLayer.h"#include "Basemap.h"#include "Envelope.h"#include "Error.h"#include "FeatureLayer.h"#include "GenerateGeodatabaseJob.h"#include "GenerateGeodatabaseParameters.h"#include "GenerateLayerOption.h"#include "Geodatabase.h"#include "GeodatabaseFeatureTable.h"#include "GeodatabaseSyncTask.h"#include "GeometryEngine.h"#include "IdInfo.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapViewTypes.h"#include "Point.h"#include "ServiceFeatureTable.h"#include "SpatialReference.h"#include "TaskTypes.h"#include "TileCache.h"#include "Viewpoint.h"
// Qt headers#include <QFuture>#include <QStandardPaths>#include <QUrl>#include <QtCore/qglobal.h>
using namespace Esri::ArcGISRuntime;
// helper method to get cross platform data pathnamespace{ QString defaultDataPath() { QString dataPath;
#ifdef Q_OS_IOS dataPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); #else dataPath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); #endif
return dataPath; }} // namespace
GenerateGeodatabaseReplicaFromFeatureService::GenerateGeodatabaseReplicaFromFeatureService(QQuickItem* parent) : QQuickItem(parent), m_dataPath(defaultDataPath() + "/ArcGIS/Runtime/Data/"){}
GenerateGeodatabaseReplicaFromFeatureService::~GenerateGeodatabaseReplicaFromFeatureService() = default;
void GenerateGeodatabaseReplicaFromFeatureService::init(){ qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<GenerateGeodatabaseReplicaFromFeatureService>("Esri.Samples", 1, 0, "GenerateGeodatabaseReplicaFromFeatureServiceSample");}
void GenerateGeodatabaseReplicaFromFeatureService::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); //! [Create a map using a local tile package]
// 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);
//! [Features GenerateGeodatabase Part 1] // create the GeodatabaseSyncTask m_syncTask = new GeodatabaseSyncTask(QUrl(m_featureServiceUrl), this); //! [Features GenerateGeodatabase Part 1]
// connect to sync task doneLoading signal connect(m_syncTask, &GeodatabaseSyncTask::doneLoading, this, [this](const Error& error) { if (!error.isEmpty()) { emit updateStatus("Generate failed"); emit hideWindow(5000, false); return; }
// add online feature layers to the map, and obtain service IDs m_featureServiceInfo = m_syncTask->featureServiceInfo(); const auto infos = m_featureServiceInfo.layerInfos(); for (const IdInfo& idInfo : infos) { // get the layer ID from the idInfo QString id = QString::number(idInfo.infoId());
// add the layer to the map QUrl featureLayerUrl(m_featureServiceInfo.url().toString() + "/" + id); ServiceFeatureTable* serviceFeatureTable = new ServiceFeatureTable(featureLayerUrl, this); FeatureLayer* featureLayer = new FeatureLayer(serviceFeatureTable, this); m_map->operationalLayers()->append(featureLayer);
// add the layer id to the string list m_serviceIds << id; }
});
// connect to map doneLoading signal connect(m_map, &Map::doneLoading, this, [this](const Error& error) { if (error.isEmpty()) { // load the sync task once the map loads m_syncTask->load(); } });}
void GenerateGeodatabaseReplicaFromFeatureService::addFeatureLayers(const QString& serviceUrl, const QStringList& serviceIds){ for (const QString& id : serviceIds) { ServiceFeatureTable* serviceFeatureTable = new ServiceFeatureTable(QUrl(serviceUrl + id), this); FeatureLayer* featureLayer = new FeatureLayer(serviceFeatureTable, this); m_map->operationalLayers()->append(featureLayer); }}
//! [Features GenerateGeodatabase Part 2]GenerateGeodatabaseParameters GenerateGeodatabaseReplicaFromFeatureService::getUpdatedParameters(Envelope gdbExtent){ // create the parameters GenerateGeodatabaseParameters params; params.setReturnAttachments(false); params.setOutSpatialReference(SpatialReference::webMercator()); params.setExtent(gdbExtent);
// set the layer options for all of the service IDs QList<GenerateLayerOption> layerOptions; for (const QString& id : std::as_const(m_serviceIds)) { GenerateLayerOption generateLayerOption(id.toInt()); layerOptions << generateLayerOption; } params.setLayerOptions(layerOptions);
return params;}
void GenerateGeodatabaseReplicaFromFeatureService::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 Envelope geodatabaseExtent = geometry_cast<Envelope>(GeometryEngine::project(extent, SpatialReference::webMercator()));
// get the updated parameters GenerateGeodatabaseParameters params = getUpdatedParameters(geodatabaseExtent);
// execute the task and obtain the job const QString outputGdb = m_tempPath.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: emit updateStatus("Complete"); emit hideWindow(1500, true); addOfflineData(generateJob->result()); break; default: break; } });
// start the generate job generateJob->start(); } else { emit updateStatus("Generate failed"); emit hideWindow(5000, false); }}//! [Features GenerateGeodatabase Part 2]
void GenerateGeodatabaseReplicaFromFeatureService::addOfflineData(Geodatabase* gdb){ // remove the original online feature layers m_map->operationalLayers()->clear();
// load the geodatabase connect(gdb, &Geodatabase::doneLoading, this, [this, gdb](Error) { // create a feature layer from each feature table, and add to the map const auto tables = gdb->geodatabaseFeatureTables(); for (GeodatabaseFeatureTable* featureTable : tables) { FeatureLayer* featureLayer = new FeatureLayer(featureTable, this); m_map->operationalLayers()->append(featureLayer); }
// unregister geodatabase since there will be no edits uploaded auto unregisterFuture = m_syncTask->unregisterGeodatabaseAsync(gdb); Q_UNUSED(unregisterFuture) }); gdb->load();}// [WriteFile Name=GenerateGeodatabaseReplicaFromFeatureService, Category=Features]// [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]
#ifndef GENERATE_GEODATABASE_H#define GENERATE_GEODATABASE_H
// ArcGIS Maps SDK headers#include "ArcGISFeatureServiceInfo.h"#include "Envelope.h"#include "GenerateGeodatabaseParameters.h"
// Qt headers#include <QQuickItem>#include <QStringList>#include <QTemporaryDir>
namespace Esri::ArcGISRuntime{ class Map; class MapQuickView; class GeodatabaseSyncTask; class Geodatabase;}
class GenerateGeodatabaseReplicaFromFeatureService : public QQuickItem{ Q_OBJECT
public: explicit GenerateGeodatabaseReplicaFromFeatureService(QQuickItem* parent = nullptr); ~GenerateGeodatabaseReplicaFromFeatureService() override;
void componentComplete() override; static void init(); Q_INVOKABLE void generateGeodatabaseFromCorners(double xCorner1, double yCorner1, double xCorner2, double yCorner2);
signals: void updateStatus(QString status); void hideWindow(int time, bool success);
private: void addFeatureLayers(const QString& serviceUrl, const QStringList& serviceIds); Esri::ArcGISRuntime::GenerateGeodatabaseParameters getUpdatedParameters(Esri::ArcGISRuntime::Envelope gdbExtent); void addOfflineData(Esri::ArcGISRuntime::Geodatabase* gdb);
private: Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::GeodatabaseSyncTask* m_syncTask = nullptr; QString m_dataPath; QString m_featureServiceUrl = QStringLiteral("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/WildfireSync/FeatureServer/"); QStringList m_serviceIds; Esri::ArcGISRuntime::ArcGISFeatureServiceInfo m_featureServiceInfo; QTemporaryDir m_tempPath;};
#endif // GENERATE_GEODATABASE_H// [WriteFile Name=GenerateGeodatabaseReplicaFromFeatureService, Category=Features]// [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]
import QtQuickimport QtQuick.Controlsimport Esri.Samples
GenerateGeodatabaseReplicaFromFeatureServiceSample { id: generateSample width: 800 height: 600
property string statusText: ""
// add a mapView component MapView { id: mapView anchors.fill: parent objectName: "mapView"
Component.onCompleted: { // Set the focus on MapView to initially enable keyboard navigation forceActiveFocus(); } }
onHideWindow: (time, success) => { generateWindow.hideWindow(time);
if (success) { extentRectangle.visible = false; downloadButton.visible = false; } }
onUpdateStatus: status => statusText = status;
Rectangle { id: extentRectangle anchors.centerIn: parent width: parent.width - 50 height: parent.height - 125 color: "transparent" border { color: "red" width: 3 } }
// Create the download button to generate geodatabase Rectangle { id: downloadButton property bool pressed: false anchors { horizontalCenter: parent.horizontalCenter bottom: parent.bottom bottomMargin: 23 }
width: 200 height: 35 color: pressed ? "#959595" : "#D6D6D6" radius: 8 border { color: "#585858" width: 1 }
Row { anchors.fill: parent spacing: 5 Image { width: 38 height: width source: "qrc:/Samples/Features/GenerateGeodatabaseReplicaFromFeatureService/download.png" }
Text { anchors.verticalCenter: parent.verticalCenter text: "Generate Geodatabase" font.pixelSize: 14 color: "#474747" } }
MouseArea { anchors.fill: parent onPressed: downloadButton.pressed = true onReleased: downloadButton.pressed = false onClicked: { generateSample.generateGeodatabaseFromCorners(extentRectangle.x, extentRectangle.y, (extentRectangle.x + extentRectangle.width), (extentRectangle.y + extentRectangle.height)); generateWindow.visible = true; } } }
// Create a window to display the generate window Rectangle { id: generateWindow anchors.fill: parent color: "transparent" visible: false clip: true
Rectangle { anchors.fill: parent color: "#60000000" }
MouseArea { anchors.fill: parent onClicked: mouse => mouse.accepted = true onWheel: wheel => wheel.accepted = true }
Rectangle { anchors.centerIn: parent width: 125 height: 100 color: "lightgrey" opacity: 0.8 radius: 5 border { color: "#4D4D4D" width: 1 }
Column { anchors { fill: parent margins: 10 } spacing: 10
BusyIndicator { anchors.horizontalCenter: parent.horizontalCenter }
Text { anchors.horizontalCenter: parent.horizontalCenter text: statusText font.pixelSize: 16 } } }
Timer { id: hideWindowTimer
onTriggered: generateWindow.visible = false; }
function hideWindow(time) { hideWindowTimer.interval = time; hideWindowTimer.restart(); } }}// [Legal]// Copyright 2015 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]
// sample headers#include "GenerateGeodatabaseReplicaFromFeatureService.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QCommandLineParser>#include <QDir>#include <QGuiApplication>#include <QQmlEngine>#include <QQuickView>#include <QSettings>
// Platform specific headers#ifdef Q_OS_WIN#include <Windows.h>#endif
#define STRINGIZE(x) #x#define QUOTE(x) STRINGIZE(x)
int main(int argc, char *argv[]){ Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setUseLegacyAuthentication(false); QGuiApplication app(argc, argv); app.setApplicationName(QString("GenerateGeodatabaseReplicaFromFeatureService"));
// Use of ArcGIS location services, such as basemap styles, geocoding, and routing services, // requires an access token. For more information see // https://links.esri.com/arcgis-runtime-security-auth.
// The following methods grant an access token:
// 1. User authentication: Grants a temporary access token associated with a user's ArcGIS account. // To generate a token, a user logs in to the app with an ArcGIS account that is part of an // organization in ArcGIS Online or ArcGIS Enterprise.
// 2. API key authentication: Get a long-lived access token that gives your application access to // ArcGIS location services. Go to the tutorial at https://links.esri.com/create-an-api-key. // Copy the API Key access token.
const QString accessToken = QString("");
if (accessToken.isEmpty()) { qWarning() << "Use of ArcGIS location services, such as the basemap styles service, requires" << "you to authenticate with an ArcGIS account or set the API Key property."; } else { Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setApiKey(accessToken); }
// Initialize the sample GenerateGeodatabaseReplicaFromFeatureService::init();
// Initialize application view QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView);
// Add the import Path view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml"));
QString arcGISRuntimeImportPath = QUOTE(ARCGIS_RUNTIME_IMPORT_PATH);
#if defined(LINUX_PLATFORM_REPLACEMENT) // on some linux platforms the string 'linux' is replaced with 1 // fix the replacement paths which were created QString replaceString = QUOTE(LINUX_PLATFORM_REPLACEMENT); arcGISRuntimeImportPath = arcGISRuntimeImportPath.replace(replaceString, "linux", Qt::CaseSensitive); #endif
// Add the Runtime and Extras path view.engine()->addImportPath(arcGISRuntimeImportPath);
// Set the source view.setSource(QUrl("qrc:/Samples/Features/GenerateGeodatabaseReplicaFromFeatureService/GenerateGeodatabaseReplicaFromFeatureService.qml"));
view.show();
return app.exec();}