Take a map offline using a preplanned map area.

Use case
Generating offline maps on demand for a specific area can be time consuming for users and a processing load on the server. If areas of interest are known ahead of time, a web map author can pre-create packages for these areas. This way, the generation only needs to happen once, making the workflow more efficient for users and servers.
An archaeology team could define preplanned map areas for dig sites which can be taken offline for field use.
How to use the sample
Select a map area from the Preplanned Map Areas list. Click the Download button to download the selected area. The download progress will be displayed through a progress bar. When a download is complete, select it to display the offline map in the map view.
How it works
- Open the online
Mapfrom aPortalItemand display it. - Create an
OfflineMapTaskusing the portal item. - Get the
PreplannedMapAreas from the task, and then load them. - To download a selected map area, create the default
DownloadPreplannedOfflineMapParametersfrom the task using the selected preplanned map area. - Set the update mode of the preplanned map area.
- Use the parameters and a download path to create a
DownloadPreplannedOfflineMapJobfrom the task. - Start the job. Once it has completed, get the
DownloadPreplannedOfflineMapResult. - Get the map from the result and display it in the
MapView.
Relevant API
- DownloadPreplannedOfflineMapJob
- DownloadPreplannedOfflineMapParameters
- DownloadPreplannedOfflineMapResult
- OfflineMapTask
- PreplannedMapArea
About the data
The Naperville stormwater network map is based on ArcGIS Solutions for Stormwater and provides a realistic depiction of a theoretical stormwater network.
Additional information
PreplannedUpdateMode can be used to set the way the preplanned map area receives updates in several ways:
NoUpdates- No updates will be performed. This mode is intended for when a static snapshot of the data is required, and it does not create a replica. This is the mode used for this sample.SyncWithFeatureServices- Changes, including local edits, will be synced directly with the underlying feature services. This is the default update mode.DownloadScheduledUpdates- Scheduled, read-only updates will be downloaded from the online map area and applied to the local mobile geodatabases.
For more information about offline workflows, see Offline maps, scenes, and data in the ArcGIS Developers guide.
Tags
map area, offline, pre-planned, preplanned
Sample Code
// [WriteFile Name=DownloadPreplannedMap, 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 "DownloadPreplannedMap.h"
// ArcGIS Maps SDK headers#include "DownloadPreplannedOfflineMapJob.h"#include "DownloadPreplannedOfflineMapResult.h"#include "Error.h"#include "Geometry.h"#include "Graphic.h"#include "GraphicListModel.h"#include "GraphicsOverlay.h"#include "GraphicsOverlayListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "MobileMapPackage.h"#include "OfflineMapTask.h"#include "OfflineMapTypes.h"#include "PortalItem.h"#include "PreplannedMapArea.h"#include "PreplannedMapAreaListModel.h"#include "SimpleLineSymbol.h"#include "SimpleRenderer.h"#include "SymbolTypes.h"#include "TaskTypes.h"
// Qt headers#include <QFuture>#include <QUuid>
using namespace Esri::ArcGISRuntime;
DownloadPreplannedMap::DownloadPreplannedMap(QObject* parent /* = nullptr */): QObject(parent), m_graphicsOverlay(new GraphicsOverlay(this)), m_portalItem(new PortalItem("acc027394bc84c2fb04d1ed317aac674", this)), m_lineSymbol(new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, QColor(Qt::red), 5, this)), m_busy(true){ m_graphicsOverlay->setRenderer(new SimpleRenderer(m_lineSymbol, this));
connect(m_portalItem, &PortalItem::doneLoading, this, [this] () { m_offlineMapTask = new OfflineMapTask(m_map, this); m_mapView->graphicsOverlays()->append(m_graphicsOverlay);
connect(m_offlineMapTask, &OfflineMapTask::doneLoading, this, [this] () { // fetch preplanned map areas from the portal item m_offlineMapTask->preplannedMapAreasAsync().then(this, [this](const QList<PreplannedMapArea*>&) { loadPreplannedMapAreas(); }); });
// Load offline map task. m_offlineMapTask->load(); });
m_map = new Map(m_portalItem, this);}
DownloadPreplannedMap::~DownloadPreplannedMap() = default;
void DownloadPreplannedMap::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<DownloadPreplannedMap>("Esri.Samples", 1, 0, "DownloadPreplannedMapSample"); qmlRegisterUncreatableType<PreplannedMapAreaListModel>("Esri.Samples", 1, 0, "AbstractListModel", "DownloadPreplannedMapSample");}
MapQuickView* DownloadPreplannedMap::mapView() const{ return m_mapView;}
// Set the view (created in QML)void DownloadPreplannedMap::setMapView(MapQuickView* mapView){ if (!mapView || mapView == m_mapView) return;
m_mapView = mapView; m_mapView->setMap(m_map);
emit mapViewChanged();}
void DownloadPreplannedMap::checkIfMapAreaIsLoaded(int index){ if (!m_offlineMapTask) return;
if (m_offlineMapTask->preplannedMapAreaList()->isEmpty()) return;
PreplannedMapArea* mapArea = m_offlineMapTask->preplannedMapAreaList()->at(index);
if (!mapArea || mapArea->loadStatus() != LoadStatus::Loaded) return;
m_busy = true; m_viewingOnlineMaps = false; emit busyChanged(); emit viewingOnlineMapsChanged();
if(m_graphicsOverlay->isVisible()) m_graphicsOverlay->setVisible(false);
loadSelectedMap(index);}
void DownloadPreplannedMap::loadSelectedMap(int index){ checkIfMapExists(index);
if (m_preplannedMapExists) loadExistingPreplannedMap(); else m_offlineMapTask->createDefaultDownloadPreplannedOfflineMapParametersAsync(m_offlineMapTask->preplannedMapAreaList()->at(index)).then(this, [this](const DownloadPreplannedOfflineMapParameters& parameters) { m_params = parameters;
/* Set the update mode to not receive updates. * Other options: * SyncWithFeatureServices - changes will be synced directly with the * underlying feature services. * DownloadScheduledUpdates - schedulded, read-only updates will be * downloaded and applied to the local geodatabase. */ m_params.setUpdateMode(PreplannedUpdateMode::NoUpdates);
m_preplannedMapJob = m_offlineMapTask->downloadPreplannedOfflineMap(m_params, m_path); connect(m_preplannedMapJob, &DownloadPreplannedOfflineMapJob::progressChanged, this, [this] () { m_percentDownloaded = .01 * m_preplannedMapJob->progress(); emit percentDownloadedChanged(); }); connect(m_preplannedMapJob, &DownloadPreplannedOfflineMapJob::jobDone, this, &DownloadPreplannedMap::onDownloadPreplannedMapJobCompleted);
// Start job to take preplanned map area offline. m_preplannedMapJob->start(); m_busy = false; emit busyChanged(); });}
void DownloadPreplannedMap::checkIfMapExists(int index){ if (!m_offlineMapTask) return;
if (m_offlineMapTask->preplannedMapAreaList()->isEmpty()) return;
PreplannedMapArea* mapArea = m_offlineMapTask->preplannedMapAreaList()->at(index);
if (!mapArea || mapArea->loadStatus() != LoadStatus::Loaded) return;
m_path = QString(m_tempPath.path() + "/" + mapArea->portalItem()->title()); QDir tempDir(m_path);
m_preplannedMapExists = tempDir.exists(); emit preplannedMapExistsChanged();
if (m_viewingOnlineMaps) m_mapView->setViewpointGeometryAsync(mapArea->areaOfInterest());}
void DownloadPreplannedMap::showOnlineMap(int index){ m_viewingOnlineMaps = true; emit viewingOnlineMapsChanged(); m_mapView->setMap(m_map); const Geometry areaOfInterest = m_offlineMapTask->preplannedMapAreaList()->at(index)->areaOfInterest(); m_mapView->setViewpointGeometryAsync(areaOfInterest); m_graphicsOverlay->setVisible(true);}
void DownloadPreplannedMap::onDownloadPreplannedMapJobCompleted(){ if (m_preplannedMapJob->jobStatus() != JobStatus::Succeeded) return;
m_mapView->setMap(m_preplannedMapJob->result()->offlineMap()); m_preplannedMapExists = true; emit preplannedMapExistsChanged(); m_viewingOnlineMaps = false; emit viewingOnlineMapsChanged();}
void DownloadPreplannedMap::loadPreplannedMapAreas(){ m_preplannedList = m_offlineMapTask->preplannedMapAreaList(); m_busy = false; emit preplannedListChanged(); emit busyChanged(); for (PreplannedMapArea* mapArea : *m_preplannedList) { connect(mapArea, &PreplannedMapArea::doneLoading, this, [this, mapArea] (const Error& e) { if (!e.isEmpty()) { qDebug() << e.message() << " - " << e.additionalMessage(); return; }
Graphic* areaOfInterest = new Graphic(mapArea->areaOfInterest(), this); m_graphicsOverlay->graphics()->append(areaOfInterest); });
mapArea->load(); }}
void DownloadPreplannedMap::loadExistingPreplannedMap(){ if (m_mmpk) { delete m_mmpk; m_mmpk = nullptr; }
m_mmpk = new MobileMapPackage(m_path, this);
connect(m_mmpk, &MobileMapPackage::doneLoading, this, [this] (const Error& e) { if (!e.isEmpty()) qDebug() << e.message() << " - " << e.additionalMessage();
m_mapView->setMap(m_mmpk->maps().at(0)); m_busy = false; emit busyChanged(); m_graphicsOverlay->setVisible(false); m_viewingOnlineMaps = false; emit viewingOnlineMapsChanged(); });
m_mmpk->load();}// [WriteFile Name=DownloadPreplannedMap, 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 DOWNLOADPREPLANNEDMAP_H#define DOWNLOADPREPLANNEDMAP_H
// ArcGIS Maps SDK headers#include "DownloadPreplannedOfflineMapParameters.h"
// Qt headers#include <QObject>#include <QTemporaryDir>
namespace Esri::ArcGISRuntime{class Map;class MapQuickView;class GraphicsOverlay;class PortalItem;class OfflineMapTask;class PreplannedMapArea;class DownloadPreplannedOfflineMapJob;class MobileMapPackage;class SimpleLineSymbol;class PreplannedMapAreaListModel;}
Q_MOC_INCLUDE("MapQuickView.h")Q_MOC_INCLUDE("PreplannedMapAreaListModel.h")
class DownloadPreplannedMap : public QObject{ Q_OBJECT
Q_PROPERTY(Esri::ArcGISRuntime::MapQuickView* mapView READ mapView WRITE setMapView NOTIFY mapViewChanged) Q_PROPERTY(Esri::ArcGISRuntime::PreplannedMapAreaListModel* preplannedList MEMBER m_preplannedList NOTIFY preplannedListChanged) Q_PROPERTY(bool busy MEMBER m_busy NOTIFY busyChanged) Q_PROPERTY(bool preplannedMapExists MEMBER m_preplannedMapExists NOTIFY preplannedMapExistsChanged) Q_PROPERTY(bool viewingOnlineMaps MEMBER m_viewingOnlineMaps NOTIFY viewingOnlineMapsChanged()) Q_PROPERTY(double percentDownloaded MEMBER m_percentDownloaded NOTIFY percentDownloadedChanged())
public: explicit DownloadPreplannedMap(QObject* parent = nullptr); ~DownloadPreplannedMap();
static void init(); Q_INVOKABLE void checkIfMapExists(int index); Q_INVOKABLE void showOnlineMap(int index); Q_INVOKABLE void checkIfMapAreaIsLoaded(int index);
signals: void mapViewChanged(); void preplannedListChanged(); void busyChanged(); void preplannedMapExistsChanged(); void viewingOnlineMapsChanged(); void percentDownloadedChanged();
private slots: void onDownloadPreplannedMapJobCompleted(); void loadPreplannedMapAreas();
private: Esri::ArcGISRuntime::MapQuickView* mapView() const; void setMapView(Esri::ArcGISRuntime::MapQuickView* mapView);
void loadSelectedMap(int index); void loadExistingPreplannedMap();
Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::GraphicsOverlay* m_graphicsOverlay = nullptr; Esri::ArcGISRuntime::OfflineMapTask* m_offlineMapTask = nullptr; Esri::ArcGISRuntime::PortalItem* m_portalItem = nullptr; Esri::ArcGISRuntime::DownloadPreplannedOfflineMapJob* m_preplannedMapJob = nullptr; Esri::ArcGISRuntime::MobileMapPackage* m_mmpk = nullptr; Esri::ArcGISRuntime::SimpleLineSymbol* m_lineSymbol = nullptr; Esri::ArcGISRuntime::PreplannedMapAreaListModel* m_preplannedList = nullptr; Esri::ArcGISRuntime::DownloadPreplannedOfflineMapParameters m_params; bool m_busy = false; bool m_mapExists = false; bool m_preplannedMapExists = false; bool m_viewingOnlineMaps = true; double m_percentDownloaded = 0.0; QString m_path; QTemporaryDir m_tempPath;};
#endif // DOWNLOADPREPLANNEDMAP_H// [WriteFile Name=DownloadPreplannedMap, 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
Item {
// add a mapView component MapView { id: view anchors.fill: parent
Component.onCompleted: { // Set the focus on MapView to initially enable keyboard navigation forceActiveFocus(); } }
// Declare the C++ instance which creates the map etc. and supply the view DownloadPreplannedMapSample { id: model mapView: view }
Rectangle { id: buttonBackground anchors { left: parent.left top: parent.top margins: 3 } width: childrenRect.width height: childrenRect.height color: "#000000" opacity: .8 radius: 5
// catch mouse signals from propagating to parent MouseArea { anchors.fill: parent onClicked: mouse => mouse.accepted = true onWheel: wheel => wheel.accepted = true }
ColumnLayout { width: 250 spacing: 0 Button { Layout.fillWidth: true Layout.margins: 1 Layout.alignment: Qt.AlignHCenter enabled: !busy.visible & !model.viewingOnlineMaps & !progressBar_loading.visible text: qsTr("Show Online Map") onClicked: model.showOnlineMap(preplannedCombo.currentIndex); }
Text { text: qsTr("Available Preplanned Areas:") color: "white" Layout.alignment: Qt.AlignHCenter }
ComboBox { id: preplannedCombo Layout.fillWidth: true Layout.margins: 1 enabled: !busy.visible & !progressBar_loading.visible model: model.preplannedList textRole: "itemTitle" onActivated: model.checkIfMapExists(preplannedCombo.currentIndex);
// Add a background to the ComboBox Rectangle { anchors.fill: parent radius: 10 // Make the rectangle visible if a dropdown indicator exists // An indicator only exists if a theme is set visible: parent.indicator border.width: 1 } }
Button { id: downloadOrView Layout.fillWidth: true Layout.margins: 1 enabled: !busy.visible & !progressBar_loading.visible text: model.preplannedMapExists ? qsTr("View preplanned area") : qsTr("Download preplanned area") onClicked: model.checkIfMapAreaIsLoaded(preplannedCombo.currentIndex); }
Text { text: qsTr("Download(s) deleted on exit") color: "white" Layout.alignment: Qt.AlignHCenter Layout.margins: 1 } } }
BusyIndicator { id: busy anchors.centerIn: parent visible: model.busy }
ProgressBar { id: progressBar_loading anchors.centerIn: parent visible: (value !== 0.0 && value !== 1.0) value: model.percentDownloaded }}// [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 "DownloadPreplannedMap.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QDir>#include <QGuiApplication>#include <QQmlApplicationEngine>
// 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("DownloadPreplannedMap"));
// 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 DownloadPreplannedMap::init();
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
// Initialize application view QQmlApplicationEngine engine; // Add the import Path engine.addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml")); // Add the Runtime and Extras path engine.addImportPath(arcGISRuntimeImportPath);
// Set the source engine.load(QUrl("qrc:/Samples/Maps/DownloadPreplannedMap/main.qml"));
return app.exec();}// Copyright 2019 ESRI//// All rights reserved under the copyright laws of the United States// and applicable international laws, treaties, and conventions.//// You may freely redistribute and use this sample code, with or// without modification, provided you include the original copyright// notice and use restrictions.//// See the Sample code usage restrictions document for further information.//
import QtQuick.Controlsimport Esri.Samples
ApplicationWindow { visible: true width: 800 height: 600
DownloadPreplannedMap { anchors.fill: parent }}