Export tiles from an online vector tile service.

Use case
Field workers with limited network connectivity can use exported vector tiles as a basemap for use while offline.
How to use the sample
When the vector tiled layer loads, zoom in to the extent you want to export. The red box shows the extent that will be exported. Click the “Export area” button to start the job. When finished, a dialog will show the exported result as a new basemap.
How it works
- Create an
ArcGISVectorTiledLayerfrom the map’s base layers. - Create an
ExportVectorTilesTaskusing the vector tiled layer’s URL. - Create default
ExportVectorTilesParametersfrom the task, specifying extent and maximum scale. - Create a
ExportVectorTilesJobfrom the task using the parameters, and specifying a vector tile cache path and an item resource path. The resource path is required if you want to export the tiles with the style. - Start the job, and once it completes successfully, get the resulting
ExportVectorTilesResult. - Get the
VectorTileCacheandItemResourceCachefrom the result to create anArcGISVectorTiledLayerthat can be displayed to the map view.
Relevant API
- ArcGISVectorTiledLayer
- ExportVectorTilesJob
- ExportVectorTilesParameters
- ExportVectorTilesResult
- ExportVectorTilesTask
- ItemResourceCache
- VectorTileCache
Additional information
NOTE: Downloading tiles for offline use requires authentication with the web map’s server. To use this sample, you will require an ArcGIS Online account.
Vector tiles have high drawing performance and smaller file size compared to regular tiled layers due to consisting solely of points, lines, and polygons. Visit Layer types on the ArcGIS Online Developer’s portal to learn more.
Tags
cache, download, offline, vector, vector tiled layer
Sample Code
// [WriteFile Name=ExportVectorTiles, Category=Layers]// [Legal]// Copyright 2022 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 "ExportVectorTiles.h"
// ArcGIS Maps SDK headers#include "ArcGISVectorTiledLayer.h"#include "Basemap.h"#include "Envelope.h"#include "Error.h"#include "ExportVectorTilesJob.h"#include "ExportVectorTilesParameters.h"#include "ExportVectorTilesResult.h"#include "ExportVectorTilesTask.h"#include "GeometryEngine.h"#include "Graphic.h"#include "GraphicListModel.h"#include "GraphicsOverlay.h"#include "GraphicsOverlayListModel.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "Point.h"#include "ServiceTypes.h"#include "SimpleLineSymbol.h"#include "SpatialReference.h"#include "SymbolTypes.h"#include "Viewpoint.h"
// Qt headers#include <QFuture>#include <QTemporaryDir>#include <QUuid>
using namespace Esri::ArcGISRuntime;
ExportVectorTiles::ExportVectorTiles(QObject* parent /* = nullptr */): QObject(parent), m_map(new Map(BasemapStyle::ArcGISStreetsNight, this)){}
ExportVectorTiles::~ExportVectorTiles() = default;
void ExportVectorTiles::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<ExportVectorTiles>("Esri.Samples", 1, 0, "ExportVectorTilesSample");}
MapQuickView* ExportVectorTiles::mapView() const{ return m_mapView;}
// Set the view (created in QML)void ExportVectorTiles::setMapView(MapQuickView* mapView){ if (!mapView || mapView == m_mapView) return;
m_mapView = mapView; m_mapView->setMap(m_map); m_mapView->setViewpointAsync(Viewpoint(34.049, -117.181, 1e4));
m_graphicsOverlay = new GraphicsOverlay(this); m_mapView->graphicsOverlays()->append(m_graphicsOverlay);
// Create the graphic that will be used to show the export extent m_exportAreaGraphic = new Graphic(this); m_exportAreaGraphic->setSymbol(new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, Qt::green, 3, this));
m_graphicsOverlay->graphics()->append(m_exportAreaGraphic);
emit mapViewChanged();}
void ExportVectorTiles::startExport(double xSW, double ySW, double xNE, double yNE){ if (!m_map->basemap() || m_map->basemap()->baseLayers()->isEmpty() || m_map->basemap()->baseLayers()->first()->layerType() != LayerType::ArcGISVectorTiledLayer) return;
// Get the first layer of the basemap baselayers as a vector tiled layer for export ArcGISVectorTiledLayer* vectorTiledLayer = static_cast<ArcGISVectorTiledLayer*>(m_map->basemap()->baseLayers()->first()); ExportVectorTilesTask* exportTask = new ExportVectorTilesTask(vectorTiledLayer->url(), this);
// Create an envelope from the QML rectangle corners const Point corner1 = m_mapView->screenToLocation(xSW, ySW); const Point corner2 = m_mapView->screenToLocation(xNE, yNE); const Envelope extent = Envelope(corner1, corner2); // Normalize the central meridian to export tiles if the export area crosses the antemeridian const Geometry exportArea = GeometryEngine::normalizeCentralMeridian(GeometryEngine::project(extent, vectorTiledLayer->spatialReference()));
m_exportAreaGraphic->setGeometry(exportArea);
// Instantiate export parameters to create the export job with exportTask->createDefaultExportVectorTilesParametersAsync(exportArea, m_mapView->mapScale() * 0.1) .then(this, [this, exportTask](ExportVectorTilesParameters exportParameters) { // Using the reduced fonts service will reduce the download size of a vtpk by around 80 Mb // It is useful for taking the basemap offline but not recommended if you plan to later upload the vtpk exportParameters.setEsriVectorTilesDownloadOption(EsriVectorTilesDownloadOption::UseReducedFontsService);
// Create a path to store the vector tile package, the file cannot already exist const QString vectorTileCachePath = m_tempDir.path() + QString("/vectorTiles%1.vtpk").arg(QDateTime::currentMSecsSinceEpoch()); // Create a path to an empty directory to store the styling resources (in this case, the night mode version of the layer) const QString itemResourcePath = m_tempDir.path() + QString("/itemResources%1").arg(QDateTime::currentMSecsSinceEpoch());
// Create a job that will download the vector tiles to the given paths m_exportJob = exportTask->exportVectorTiles(exportParameters, vectorTileCachePath, itemResourcePath);
connect(m_exportJob, &ExportVectorTilesJob::jobDone, this, [this]() { if (m_exportJob->error().isEmpty()) { VectorTileCache* vectorTileCache = m_exportJob->result()->vectorTileCache(); ItemResourceCache* itemResourceCache = m_exportJob->result()->itemResourceCache();
// Create a vector tiled layer when the download is completed ArcGISVectorTiledLayer* exportedLayer = new ArcGISVectorTiledLayer(vectorTileCache, itemResourceCache, this); m_map->setBasemap(new Basemap(exportedLayer, this)); m_isUsingOfflineBasemap = true; m_exportJob->disconnect(); } });
connect(m_exportJob, &Job::progressChanged, this, [this]() { m_exportProgress = m_exportJob->progress(); emit exportProgressChanged(); });
connect(m_exportJob, &Job::statusChanged, this, [this](JobStatus s) { m_jobStatus = static_cast<int>(s); emit jobStatusChanged(); }); m_exportJob->start(); });}
void ExportVectorTiles::cancel(){ m_exportJob->cancelJobAsync().then(this, [this](bool succeeded) { emit jobCancelDone(succeeded);; }); reset();}
void ExportVectorTiles::reset(){ if (m_isUsingOfflineBasemap) { m_map->setBasemap(new Basemap(BasemapStyle::ArcGISStreetsNight, this)); m_isUsingOfflineBasemap = false; }
m_exportAreaGraphic->setGeometry(Geometry()); m_jobStatus = 0; // Override the job status to set the UI button to "Export area" again emit jobStatusChanged();}
int ExportVectorTiles::exportProgress() const{ return m_exportProgress;}
int ExportVectorTiles::jobStatus() const{ return m_jobStatus;}// [WriteFile Name=ExportVectorTiles, Category=Layers]// [Legal]// Copyright 2022 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 EXPORTVECTORTILES_H#define EXPORTVECTORTILES_H
// Qt headers#include <QObject>#include <QTemporaryDir>
namespace Esri::ArcGISRuntime{class ExportVectorTilesJob;class Graphic;class GraphicsOverlay;class Map;class MapQuickView;}
Q_MOC_INCLUDE("MapQuickView.h")
class ExportVectorTiles : public QObject{ Q_OBJECT
Q_PROPERTY(Esri::ArcGISRuntime::MapQuickView* mapView READ mapView WRITE setMapView NOTIFY mapViewChanged) Q_PROPERTY(int exportProgress READ exportProgress NOTIFY exportProgressChanged) Q_PROPERTY(int jobStatus READ jobStatus NOTIFY jobStatusChanged)
public: explicit ExportVectorTiles(QObject* parent = nullptr); ~ExportVectorTiles();
enum ExportJobStatus { ExportStatusNotStarted, ExportStatusStarted, ExportStatusPaused, ExportStatusSucceeded, ExportStatusFailed, ExportStatusCancelling }; Q_ENUM(ExportJobStatus)
static void init();
Q_INVOKABLE void startExport(double xSW, double ySW, double xNE, double yNE); Q_INVOKABLE void cancel(); Q_INVOKABLE void reset();
signals: void mapViewChanged(); void exportProgressChanged(); void jobStatusChanged(); void jobCancelDone(bool succeeded);
private: Esri::ArcGISRuntime::MapQuickView* mapView() const; void setMapView(Esri::ArcGISRuntime::MapQuickView* mapView); int exportProgress() const; int jobStatus() const;
Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::Graphic* m_exportAreaGraphic = nullptr; Esri::ArcGISRuntime::GraphicsOverlay* m_graphicsOverlay = nullptr; Esri::ArcGISRuntime::ExportVectorTilesJob* m_exportJob = nullptr;
int m_exportProgress = 0; int m_jobStatus = 0; bool m_isUsingOfflineBasemap = false;
QTemporaryDir m_tempDir;};
#endif // EXPORTVECTORTILES_H// [WriteFile Name=ExportVectorTiles, Category=Layers]// [Legal]// Copyright 2022 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
Item { id: item
// add a mapView component MapView { id: view anchors.fill: parent
Component.onCompleted: { // Set and keep the focus on MapView to enable keyboard navigation forceActiveFocus(); } }
Rectangle { id: exportProgressWindow anchors.centerIn: parent
color: "white" visible: model.jobStatus !== 0 && model.jobStatus !== 3 && model.jobStatus !== 4
border { color: "black" width: 2 }
Column { id: exportProgressColumn anchors.centerIn: parent spacing: 10
BusyIndicator { id: busyIndicator anchors.horizontalCenter: parent.horizontalCenter running: visible }
Text { id: statusText anchors.horizontalCenter: parent.horizontalCenter text: "Export job status: " + ["Not started", "Started", "Paused", "Succeeded", "Failed", "Cancelling"][model.jobStatus] font.pixelSize: 16 }
Text { id: statusTextCanceled anchors.horizontalCenter: parent.horizontalCenter text: "Job cancelled" visible: !statusText.visible font.pixelSize: 16 }
Text { id: progressText anchors.horizontalCenter: parent.horizontalCenter text: model.exportProgress + "% Completed" font.pixelSize: 16 }
onWidthChanged: { exportProgressWindow.width = exportProgressColumn.width + 20 }
onHeightChanged: { exportProgressWindow.height = exportProgressColumn.height + 20 } } }
// Create an extent rectangle for selecting the offline area Rectangle { id: extentRectangle anchors.centerIn: parent
width: parent.width - parent.width * 0.1 height: parent.height - parent.height * 0.25 color: "transparent" border { color: "red" width: 3 } }
// Button to start the download Button { id: button anchors { bottom: parent.bottom bottomMargin: item.height * .05 horizontalCenter: parent.horizontalCenter } width: 150
text: "Export area"
onClicked: { switch(model.jobStatus) { case ExportVectorTilesSample.ExportStatusNotStarted: model.startExport(extentRectangle.x, (extentRectangle.y + extentRectangle.height), (extentRectangle.x + extentRectangle.width), extentRectangle.y); extentRectangle.visible = false; break; case ExportVectorTilesSample.ExportStatusStarted: model.cancel(); extentRectangle.visible = true; break; case ExportVectorTilesSample.ExportStatusPaused: break; case ExportVectorTilesSample.ExportStatusSucceeded: model.reset(); extentRectangle.visible = true; break; case ExportVectorTilesSample.ExportStatusFailed: model.startExport(extentRectangle.x, (extentRectangle.y + extentRectangle.height), (extentRectangle.x + extentRectangle.width), extentRectangle.y); break; case ExportVectorTilesSample.ExportStatusCancelling: break; default: break; } } }
// Declare the C++ instance which creates the map etc. and supply the view ExportVectorTilesSample { id: model mapView: view
onJobStatusChanged: { switch(model.jobStatus) { case ExportVectorTilesSample.ExportStatusNotStarted: button.text = "Export area"; break; case ExportVectorTilesSample.ExportStatusStarted: button.text = "Cancel export"; exportProgressWindow.visible = true; break; case ExportVectorTilesSample.ExportStatusPaused: break; case ExportVectorTilesSample.ExportStatusSucceeded: button.text = "Reset"; exportProgressWindow.visible = false; break; case ExportVectorTilesSample.ExportStatusFailed: button.text = "Export area"; exportProgressWindow.visible = false; break; case ExportVectorTilesSample.ExportStatusCancelling: break; default: break; } }
readonly property Timer timer: Timer { id: jobCancelDoneTimer interval: 2000 onTriggered: { exportProgressWindow.visible = false; statusText.visible = true } }
onJobCancelDone: succeeded => { statusTextCanceled.text = (succeeded ? "Job canceled successfully" : "Job failed to cancel successfully"); exportProgressWindow.visible = true; statusText.visible = false; jobCancelDoneTimer.start(); } }}// [Legal]// Copyright 2022 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 "ExportVectorTiles.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QCommandLineParser>#include <QDir>#include <QGuiApplication>#include <QQmlApplicationEngine>
// Platform specific headers#ifdef Q_OS_WIN#include <Windows.h>#endif
int main(int argc, char *argv[]){ Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setUseLegacyAuthentication(false); QGuiApplication app(argc, argv); app.setApplicationName(QString("ExportVectorTiles"));
// 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 ExportVectorTiles::init();
// Initialize application view QQmlApplicationEngine engine; // Add the import Path engine.addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml"));
#ifdef ARCGIS_RUNTIME_IMPORT_PATH_2 engine.addImportPath(ARCGIS_RUNTIME_IMPORT_PATH_2);#endif
// Set the source engine.load(QUrl("qrc:/Samples/Layers/ExportVectorTiles/main.qml"));
return app.exec();}// Copyright 2022 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.
import QtQuick.Controlsimport Esri.Samples
ApplicationWindow { visible: true width: 800 height: 600
ExportVectorTiles { anchors.fill: parent }}