Download tiles to a local tile cache file stored on the device.

Use case
Field workers with limited network connectivity can use exported tiles as a basemap for use offline.
How to use the sample
Pan and zoom into the desired area, making sure the area is within the red boundary. Click ‘Export tiles’ to start the process. The application will export tiles from the raster imagery baselayer and not include the vector labels baselayer from the Imagery BasemapStyle. On successful completion you will see a preview of the downloaded tile package.
How it works
- Create an
ArcGISTiledLayerfrom a raster baselayer of a basemap style. - Create an
ExportTileCacheTask, passing in the URL of the tiled layer. - Create default
ExportTileCacheParametersfor the task, specifying extent, minimum scale and maximum scale. Limiting the difference between the minimum and maximum scales will decrease the size of the resulting tile package and the time it takes to create. - Use the parameters and a path to create an
ExportTileCacheJobfrom the task. - Start the job, and when it completes successfully, get the resulting
TileCache. - Use the tile cache to create an
ArcGISTiledLayer, and display it in the map.
Relevant API
- ArcGISTiledLayer
- ExportTileCacheJob
- ExportTileCacheParameters
- ExportTileCacheTask
- TileCache
Additional information
ArcGIS tiled layers do not support reprojection, query, select, identify, or editing. See the Layer types discussion in the developers guide to learn more about the characteristics of ArcGIS tiled layers.
At this time, ExportTileCacheTask only supports raster layers.
Tags
cache, download, offline
Sample Code
// [WriteFile Name=ExportTiles, Category=Layers]// [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 "ExportTiles.h"
// ArcGIS Maps SDK headers#include "ArcGISTiledLayer.h"#include "Basemap.h"#include "Envelope.h"#include "Error.h"#include "ExportTileCacheJob.h"#include "ExportTileCacheParameters.h"#include "ExportTileCacheTask.h"#include "GeometryEngine.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "Point.h"#include "SpatialReference.h"#include "TaskTypes.h"#include "TileCache.h"#include "Viewpoint.h"
// Qt headers#include <QFuture>#include <QUrl>#include <QUuid>
using namespace Esri::ArcGISRuntime;
ExportTiles::ExportTiles(QQuickItem* parent) : QQuickItem(parent){}
ExportTiles::~ExportTiles() = default;
void ExportTiles::init(){ qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<ExportTiles>("Esri.Samples", 1, 0, "ExportTilesSample");}
void ExportTiles::componentComplete(){ QQuickItem::componentComplete();
// find QML MapView component m_mapView = findChild<MapQuickView*>("mapView");
// create a tiled basemap Basemap* basemap = new Basemap(BasemapStyle::ArcGISImagery, this);
// create an export tile cache task when basemap has finished loading connect(basemap, &Basemap::doneLoading, this, [this]() { if (!m_map->basemap()->baseLayers()->isEmpty()) createExportTileCacheTask(); });
// create a new map instance m_map = new Map(basemap, this);
// set an initial viewpoint m_map->setInitialViewpoint(Viewpoint(35, -117, 1e7));
// set map on the map view m_mapView->setMap(m_map);}
void ExportTiles::createExportTileCacheTask(){ // Get a tile layer from the basemap ArcGISTiledLayer* tiledLayer = dynamic_cast<ArcGISTiledLayer*>(m_map->basemap()->baseLayers()->at(0));
// create the task with the url and load it m_exportTileCacheTask = new ExportTileCacheTask(tiledLayer->url(), this);
connect(m_exportTileCacheTask, &ExportTileCacheTask::doneLoading, this, [this](const Error& error) { if (!error.isEmpty()) { emit updateStatus("Export failed"); emit hideWindow(5000, false); } });
m_exportTileCacheTask->load();}
void ExportTiles::exportTileCacheFromCorners(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 tileCacheExtent = GeometryEngine::project(extent, SpatialReference::webMercator());
// generate parameters m_exportTileCacheTask->createDefaultExportTileCacheParametersAsync(tileCacheExtent, m_mapView->mapScale(), m_mapView->mapScale() * 0.1) .then(this, [this](const ExportTileCacheParameters& parameters) { onDefaultExportTileCacheParametersCompleted_(parameters); });}
void ExportTiles::onDefaultExportTileCacheParametersCompleted_(const ExportTileCacheParameters& parameters){ //! [ExportTiles start job] // execute the task and obtain the job ExportTileCacheJob* exportJob = m_exportTileCacheTask->exportTileCache(parameters, m_tempPath.path() + "/offlinemap.tpkx");
// check if there is a valid job if (exportJob) { connect(exportJob, &ExportTileCacheJob::progressChanged, this, [this, exportJob]() { m_exportTilesProgress = exportJob->progress(); emit exportTilesProgressChanged(); });
// connect to the job's status changed signal connect(exportJob, &ExportTileCacheJob::statusChanged, this, [this, exportJob](JobStatus jobStatus) { // connect to the job's status changed signal to know once it is done switch (jobStatus) { case JobStatus::Failed: emit updateStatus("Export 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("Adding TPKX..."); emit hideWindow(1500, true); displayOutputTileCache(exportJob->result()); break; default: break; } });
// start the export job exportJob->start(); } //! [ExportTiles start job] else { emit updateStatus("Export failed"); emit hideWindow(5000, false); }}
// display the tile cache once the task is completevoid ExportTiles::displayOutputTileCache(TileCache* tileCache){ // create a new tiled layer from the output tile cache ArcGISTiledLayer* tiledLayer = new ArcGISTiledLayer(tileCache, this);
// add the new layer to a basemap Basemap* basemap = new Basemap(tiledLayer, this);
// set the new basemap on the map m_map->setBasemap(basemap);
// zoom to the new layer and hide window once loaded connect(tiledLayer, &ArcGISTiledLayer::doneLoading, this, [this, tiledLayer]() { if (tiledLayer->loadStatus() == LoadStatus::Loaded) { const double prevMapScale = m_mapView->mapScale(); m_map->setMinScale(prevMapScale); m_map->setMaxScale(prevMapScale * 0.1); m_mapView->setViewpointScaleAsync(prevMapScale * 0.5); } });}// [WriteFile Name=ExportTiles, Category=Layers]// [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 EXPORT_TILES#define EXPORT_TILES
// Qt headers#include <QQuickItem>#include <QTemporaryDir>
namespace Esri::ArcGISRuntime{ class ExportTileCacheParameters; class ExportTileCacheTask; class Map; class MapQuickView; class TileCache;}
class ExportTiles : public QQuickItem{ Q_OBJECT
public: explicit ExportTiles(QQuickItem* parent = nullptr); ~ExportTiles() override;
void componentComplete() override; static void init(); Q_INVOKABLE void exportTileCacheFromCorners(double xCorner1, double yCorner1, double xCorner2, double yCorner2); Q_PROPERTY(int exportTilesProgress READ exportTilesProgress NOTIFY exportTilesProgressChanged)
signals: void updateStatus(QString status); void hideWindow(int time, bool success); void exportTilesProgressChanged();
private: void createExportTileCacheTask(); void displayOutputTileCache(Esri::ArcGISRuntime::TileCache* tileCache); inline int exportTilesProgress() { return m_exportTilesProgress; } void onDefaultExportTileCacheParametersCompleted_(const Esri::ArcGISRuntime::ExportTileCacheParameters& parameters);
Esri::ArcGISRuntime::ExportTileCacheTask* m_exportTileCacheTask = nullptr; Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; QTemporaryDir m_tempPath; int m_exportTilesProgress = 0;};
#endif // EXPORT_TILES// [WriteFile Name=ExportTiles, Category=Layers]// [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
ExportTilesSample { id: exportTilesSample 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) => { exportWindow.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 export tile cache Rectangle { id: downloadButton property bool pressed: false anchors { horizontalCenter: parent.horizontalCenter bottom: parent.bottom bottomMargin: 23 }
width: 130 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/Layers/ExportTiles/download.png" } Text { anchors.verticalCenter: parent.verticalCenter text: "Export tiles" font.pixelSize: 14 color: "#474747" } }
MouseArea { anchors.fill: parent onPressed: downloadButton.pressed = true onReleased: downloadButton.pressed = false onClicked: { // call the C++ invokable function to export tile cache from the input screen coordinates exportTilesSample.exportTileCacheFromCorners(extentRectangle.x, extentRectangle.y, (extentRectangle.x + extentRectangle.width), (extentRectangle.y + extentRectangle.height)); exportWindow.visible = true; } } }
// Create a window to display the export window Rectangle { id: exportWindow 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: 140 height: 145 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 }
Text { anchors.horizontalCenter: parent.horizontalCenter text: exportTilesSample.exportTilesProgress + "% Completed" font.pixelSize: 16 } } }
Timer { id: hideWindowTimer
onTriggered: exportWindow.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 "ExportTiles.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("ExportTiles"));
// 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 ExportTiles::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/Layers/ExportTiles/ExportTiles.qml"));
view.show();
return app.exec();}