Use the OfflineMapTask to take a web map offline, but instead of downloading an online basemap, use one which is already on the device.

Use case
There are a number of use-cases where you may wish to use a basemap which is already on the device, rather than downloading:
- You want to limit the total download size.
- You want to be able to share a single set of basemap files between many offline maps.
- You want to use a custom basemap (for example authored in ArcGIS Pro) which is not available online.
- You do not wish to sign into ArcGIS.com in order to download Esri basemaps.
The author of a web map can support the use of basemaps which are already on a device by configuring the web map to specify the name of a suitable basemap file. This could be a basemap which:
- Has been authored in ArcGIS Pro to make use of your organization’s custom data.
- Is available as a PortalItem which can be downloaded once and re-used many times.
How to use the sample
- Click on “Generate Offline Map”.
- You will be prompted to choose whether you wish to download the online basemap or use the “naperville_imagery.tpkx” basemap which is already on the device.
- If you choose to download the online basemap, the offline map will be generated with the same (topographic) basemap as the online web map.
- If you choose to use the basemap from the device, the offline map will be generated with the local imagery basemap. The download will be quicker since no tiles are exported or downloaded.
- Since the application is not exporting online ArcGIS Online basemaps you will not need to log-in.
How it works
- The sample creates a
PortalItemobject using a web map’s ID. This portal item is used to initialize anOfflineMapTaskobject. When the button is clicked, the sample requests the default parameters for the task, with the selected extent, by callingOfflineMapTask::createDefaultGenerateOfflineMapParameters. - If the user chooses to use the basemap on the device, the
GenerateOfflineMapParameters::referenceBasemapDirectoryis set to the absolute path of the directory which contains the .tpkx file. - A
GenerateOfflineMapJobis created by callingOfflineMapTask::generateOfflineMappassing the parameters and the download location for the offline map. - When the
GenerateOfflineMapJobis started it will check whetherGenerateOfflineMapParameters::referenceBasemapDirectoryhas been set. If this property is set, no online basemap will be downloaded and instead, the mobile map will be created with a reference to the .tpkx on the device.
Relevant API
- GenerateOfflineMapJob
- GenerateOfflineMapParameters
- GenerateOfflineMapResult
- OfflineMapTask
Offline data
Read more about how to set up the sample’s offline data here.
| Link | Local Location |
|---|---|
| Naperville Imagery Tile Package | <userhome>/ArcGIS/Runtime/Data/tpkx/naperville_imagery.tpkx |
Tags
basemap, download, local, offline, save, web map
Sample Code
// Copyright 2019 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
// Create the download button to export the tile cacheRectangle { property bool pressed: false signal buttonClicked()
width: 190 height: 35 color: pressed ? "#959595" : "#D6D6D6" radius: 5 border { color: "#585858" width: 1 }
Row { anchors.fill: parent spacing: 5 Image { width: 38 height: width source: "qrc:/Samples/Maps/GenerateOfflineMapLocalBasemap/download.png" } Text { anchors.verticalCenter: parent.verticalCenter text: "Generate Offline Map" font.pixelSize: 14 color: "#474747" } }
MouseArea { anchors.fill: parent onPressed: downloadButton.pressed = true onReleased: downloadButton.pressed = false onClicked: { buttonClicked(); } }}// [WriteFile Name=GenerateOfflineMapLocalBasemap, Category=Maps]// [Legal]// Copyright 2019 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 "GenerateOfflineMapLocalBasemap.h"
// ArcGIS Maps SDK headers#include "Envelope.h"#include "Error.h"#include "GenerateOfflineMapJob.h"#include "GenerateOfflineMapParameters.h"#include "GenerateOfflineMapResult.h"#include "GeometryEngine.h"#include "Layer.h"#include "Map.h"#include "MapQuickView.h"#include "OfflineMapTask.h"#include "Point.h"#include "PortalItem.h"#include "SpatialReference.h"#include "TaskTypes.h"
// Qt headers#include <QFuture>#include <QStandardPaths>#include <QTemporaryDir>#include <QUuid>#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
const QString GenerateOfflineMapLocalBasemap::s_webMapId = QStringLiteral("acc027394bc84c2fb04d1ed317aac674");
GenerateOfflineMapLocalBasemap::GenerateOfflineMapLocalBasemap(QQuickItem* parent /* = nullptr */): QQuickItem(parent){}
void GenerateOfflineMapLocalBasemap::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<GenerateOfflineMapLocalBasemap>("Esri.Samples", 1, 0, "GenerateOfflineMapLocalBasemapSample");}
void GenerateOfflineMapLocalBasemap::componentComplete(){ QQuickItem::componentComplete();
// find QML MapView component m_mapView = findChild<MapQuickView*>("mapView");
// Create a Portal Item for use by the Map and OfflineMapTask m_portalItem = new PortalItem(webMapId(), this);
// Create a map from the Portal Item m_map = new Map(m_portalItem, this);
// Update property once map is done loading connect(m_map, &Map::doneLoading, this, [this](const Error& e) { if (!e.isEmpty()) return;
m_mapLoaded = true; emit mapLoadedChanged(); });
// Set map to map view m_mapView->setMap(m_map);
// Create the OfflineMapTask with the online map m_offlineMapTask = new OfflineMapTask(m_map, this);
// connect to the error signal connect(m_offlineMapTask, &OfflineMapTask::errorOccurred, this, [](const Error& e) { if (e.isEmpty()) return;
qDebug() << e.message() << e.additionalMessage(); });}
void GenerateOfflineMapLocalBasemap::generateMapByExtent(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 = Envelope(corner1, corner2); const Envelope mapExtent = geometry_cast<Envelope>(GeometryEngine::project(extent, SpatialReference::webMercator())); const QString tempPath = m_tempDir.path() + "/OfflineMap.mmpk"; const QString dataPath = defaultDataPath() + "/ArcGIS/Runtime/Data/tpkx";
// generate parameters m_offlineMapTask->createDefaultGenerateOfflineMapParametersAsync(mapExtent).then(this, [this, tempPath, dataPath](GenerateOfflineMapParameters params) { // update default parameters to specify use of local basemap // this will prevent new tiles from being generated on the server // and will reduce generation and download time if (m_useLocalBasemap) { params.setReferenceBasemapDirectory(dataPath); // A default reference basemap filename can be specified by the source portal item's advanced offline options. params.setReferenceBasemapFilename("naperville_imagery.tpkx"); }
// Take the map offline once the parameters are generated GenerateOfflineMapJob* generateJob = m_offlineMapTask->generateOfflineMap(params, tempPath);
// check if there is a valid job if (generateJob) { // connect to the job's status changed signal connect(generateJob, &GenerateOfflineMapJob::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: // show any layer errors if (generateJob->result()->hasErrors()) { QString layerErrors = ""; const QMap<Layer*, Error>& layerErrorsMap = generateJob->result()->layerErrors(); for (auto it = layerErrorsMap.cbegin(); it != layerErrorsMap.cend(); ++it) { layerErrors += it.key()->name() + ": " + it.value().message() + "\n"; } emit showLayerErrors(layerErrors); }
// show the map emit updateStatus("Complete"); emit hideWindow(1500, true); m_mapView->setMap(generateJob->result()->offlineMap(this)); break; default: break; } });
// connect to progress changed signal connect(generateJob, &GenerateOfflineMapJob::progressChanged, this, [this, generateJob]() { emit updateProgress(generateJob->progress()); });
// connect to the error signal connect(generateJob, &GenerateOfflineMapJob::errorOccurred, this, [](const Error& e) { if (e.isEmpty()) return;
qDebug() << e.message() << e.additionalMessage(); });
// start the generate job generateJob->start(); } else { emit updateStatus("Export failed"); emit hideWindow(5000, false); } });}// [WriteFile Name=GenerateOfflineMapLocalBasemap, Category=Maps]// [Legal]// Copyright 2019 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 GENERATEOFFLINEMAPLOCALBASEMAP_H#define GENERATEOFFLINEMAPLOCALBASEMAP_H
// Qt headers#include <QQuickItem>#include <QTemporaryDir>
namespace Esri::ArcGISRuntime{class Map;class MapQuickView;class PortalItem;class OfflineMapTask;}
class GenerateOfflineMapLocalBasemap : public QQuickItem{ Q_OBJECT
Q_PROPERTY(bool mapLoaded MEMBER m_mapLoaded NOTIFY mapLoadedChanged) Q_PROPERTY(bool useLocalBasemap MEMBER m_useLocalBasemap NOTIFY useLocalBasemapChanged)
public: explicit GenerateOfflineMapLocalBasemap(QQuickItem* parent = nullptr); ~GenerateOfflineMapLocalBasemap() override = default;
void componentComplete() override; static void init();
public: Q_INVOKABLE void generateMapByExtent(double xCorner1, double yCorner1, double xCorner2, double yCorner2);
signals: void mapLoadedChanged(); void hideWindow(int time, bool success); void updateStatus(const QString& status); void updateProgress(int progress); void showLayerErrors(const QString& error); void useLocalBasemapChanged();
private: static const QString webMapId() { return s_webMapId; }
private: Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::PortalItem* m_portalItem = nullptr; Esri::ArcGISRuntime::OfflineMapTask* m_offlineMapTask = nullptr; static const QString s_webMapId; bool m_mapLoaded = false; bool m_useLocalBasemap = false; QTemporaryDir m_tempDir;};
#endif // GENERATEOFFLINEMAPLOCALBASEMAP_H// [WriteFile Name=GenerateOfflineMapLocalBasemap, Category=Maps]// [Legal]// Copyright 2019 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 QtQuick.Layoutsimport Esri.Samples
GenerateOfflineMapLocalBasemapSample { id: offlineMapSample clip: true width: 800 height: 600
onUpdateStatus: status => generateWindow.statusText = status; onUpdateProgress: progress => generateWindow.progressText = progress; onHideWindow: (time, success) => { generateWindow.hideWindow(time);
if (success) { extentRectangle.visible = false; downloadButton.visible = false; } }
onShowLayerErrors: { msgDialog.detailedText = error; msgDialog.open(); }
// 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(); }
// Create a button and anchor it to the attribution top DownloadButton { id: downloadButton anchors { horizontalCenter: parent.horizontalCenter bottom: mapView.attributionTop margins: 5 } visible: mapLoaded
onButtonClicked: { dialog.open(); } } }
// Create an extent rectangle for selecting the offline area Rectangle { id: extentRectangle anchors.centerIn: parent width: parent.width - 50 height: parent.height - 125 color: "transparent" visible: mapLoaded border { color: "red" width: 3 } }
GenerateWindow { id: generateWindow anchors.fill: parent }
Dialog { id: msgDialog modal: true x: Math.round(parent.width - width) / 2 y: Math.round(parent.height - height) / 2 standardButtons: Dialog.Ok title: "Layer Errors" property alias text : textLabel.text property alias detailedText : detailsLabel.text ColumnLayout { Text { id: textLabel text: "Some layers could not be taken offline." } Text { id: detailsLabel } } }
Dialog { id: dialog anchors.centerIn: parent width: 200
Column { spacing: 2 width: parent.width
Text { width: parent.width horizontalAlignment: Text.AlignHCenter wrapMode: Text.Wrap text: "This web map references a local basemap with the name 'naperville_imagery.tpkx'.\nYou can use the basemap already on disk or download the basemap again" }
Button { anchors.horizontalCenter: parent.horizontalCenter text: "Use Local Basemap" onClicked: { useLocalBasemap = true; generateMapByExtent(extentRectangle.x, extentRectangle.y, (extentRectangle.x + extentRectangle.width), (extentRectangle.y + extentRectangle.height)); generateWindow.visible = true; dialog.close(); } }
Button { anchors.horizontalCenter: parent.horizontalCenter text: "Download Basemap" onClicked: { useLocalBasemap = false; generateMapByExtent(extentRectangle.x, extentRectangle.y, (extentRectangle.x + extentRectangle.width), (extentRectangle.y + extentRectangle.height)); generateWindow.visible = true; dialog.close(); } }
Button { anchors.horizontalCenter: parent.horizontalCenter text: "Cancel" onClicked: dialog.close() } } }}// Copyright 2019 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 QtQuickimport QtQuick.Controls
Rectangle { id: exportWindow color: "transparent" visible: false clip: true
property string statusText: "Starting" property string progressText: "0"
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: 135 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: "%1: %2%".arg(statusText).arg(progressText) font.pixelSize: 16 } } }
Timer { id: hideWindowTimer
onTriggered: parent.visible = false; }
function hideWindow(time) { hideWindowTimer.interval = time; hideWindowTimer.restart(); }}// [Legal]// Copyright 2019 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 "GenerateOfflineMapLocalBasemap.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QCommandLineParser>#include <QDir>#include <QGuiApplication>#include <QQmlEngine>#include <QQuickView>
// 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("GenerateOfflineMapLocalBasemap"));
// 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 GenerateOfflineMapLocalBasemap::init();
// Initialize application view QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView);
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 import Path view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml")); // Add the Runtime and Extras path view.engine()->addImportPath(arcGISRuntimeImportPath);
// Set the source view.setSource(QUrl("qrc:/Samples/Maps/GenerateOfflineMapLocalBasemap/GenerateOfflineMapLocalBasemap.qml"));
view.show();
return app.exec();}