Skip To Content ArcGIS for Developers Sign In Dashboard

ArcGIS Runtime SDK for Qt

Generate offline map with local basemap

Sample Viewer View Sample on GitHub

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

  1. Click on "Generate Offline Map".
  2. You will be prompted to choose whether you wish to download the online basemap or use the "naperville_imagery.tpk" basemap which is already on the device.
  3. If you choose to download the online basemap, the offline map will be generated with the same (topographic) basemap as the online web map.
  4. To download the Esri basemap, you may be prompted to sign in to ArcGIS.com.
  5. 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.
  6. Since the application is not exporting online ArcGIS Online basemaps you will not need to log-in.

How it works

  1. The sample creates a PortalItem object using a web map's ID. This portal item is used to initialize an OfflineMapTask object. When the button is clicked, the sample requests the default parameters for the task, with the selected extent, by calling OfflineMapTask.createDefaultGenerateOfflineMapParameters.
  2. If the user chooses to use the basemap on the device, the GenerateOfflineMapParameters.referenceBasemapDirectory is set to the absolute path of the directory which contains the .tpk file.
  3. A GenerateOfflineMapJob is created by calling OfflineMapTask.generateOfflineMap passing the parameters and the download location for the offline map.
  4. When the GenerateOfflineMapJob is started it will check whether GenerateOfflineMapParameters.referenceBasemapDirectory has 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 .tpk on the device.

Relevant API

  • OfflineMapTask
  • GenerateOfflineMapParameters
  • GenerateOfflineMapJob
  • GenerateOfflineMapResult

Offline data

Read more about how to set up the sample's offline data here.

Link Local Location
Yellowstone Mobile Map Package <userhome>/ArcGIS/Runtime/Data/tpk/naperville_imagery.tpk

Tags

basemap, download, local, offline, save, web map

Sample Code

import QtQuick 2.6
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3
import Esri.ArcGISRuntime 100.9
import Esri.ArcGISExtras 1.1
import Esri.ArcGISRuntime.Toolkit.Dialogs 100.9

Rectangle {
    id: rootRectangle
    clip: true
    width: 800
    height: 600

    readonly property url outputMapPackage: System.temporaryFolder.url + "/OfflineMap_%1.mmpk".arg(new Date().getTime().toString())
    readonly property url basemapDirectory: System.userHomePath + "/ArcGIS/Runtime/Data/tpk"
    readonly property string webMapId: "acc027394bc84c2fb04d1ed317aac674"
    property bool useLocalBasemap: false

    MapView {
        id: mapView
        anchors.fill: parent

        // Create a Map from a Portal Item
        Map {
            id: map

            PortalItem {
                id: mapPortalItem
                itemId: webMapId
            }
        }

        // Create a button and anchor it to the attribution top
        DownloadButton {
            id: downloadButton
            anchors {
                horizontalCenter: parent.horizontalCenter
                bottom: mapView.attributionTop
                margins: 5
            }
            visible: map.loadStatus === Enums.LoadStatusLoaded

            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: map.loadStatus === Enums.LoadStatusLoaded
        border {
            color: "red"
            width: 3
        }

        function getRectangleEnvelope() {
            const corner1 = mapView.screenToLocation(extentRectangle.x, extentRectangle.y);
            const corner2 = mapView.screenToLocation((extentRectangle.x + extentRectangle.width), (extentRectangle.y + extentRectangle.height));
            const envBuilder = ArcGISRuntimeEnvironment.createObject("EnvelopeBuilder");
            envBuilder.setCorners(corner1, corner2);
            const mapExtent = GeometryEngine.project(envBuilder.geometry, Factory.SpatialReference.createWebMercator());
            offlineMapTask.createDefaultGenerateOfflineMapParameters(mapExtent);
        }
    }


    // Create Offline Map Task
    OfflineMapTask {
        id: offlineMapTask
        portalItem: mapPortalItem
        property var generateJob

        onErrorChanged: console.log("error:", error.message, error.additionalMessage);

        onCreateDefaultGenerateOfflineMapParametersStatusChanged: {
            if (createDefaultGenerateOfflineMapParametersStatus !== Enums.TaskStatusCompleted)
                return;

            const parameters = offlineMapTask.createDefaultGenerateOfflineMapParametersResult;

            // 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 (useLocalBasemap) {
                // set the path where 'naperville_imagery.tpk' exists
                parameters.referenceBasemapDirectory = System.resolvedPath(basemapDirectory);
            }

            // Take the map offline
            takeMapOffline(offlineMapTask.createDefaultGenerateOfflineMapParametersResult);
        }


        function takeMapOffline(parameters) {
            // create the job
            generateJob = offlineMapTask.generateOfflineMap(parameters, outputMapPackage);

            // check if job is valid
            if (generateJob) {
                // show the export window
                generateWindow.visible = true;

                // connect to the job's status changed signal to know once it is done
                generateJob.jobStatusChanged.connect(updateJobStatus);
                // connect to the job's progress changed signal
                generateJob.progressChanged.connect(updateProgress);

                generateJob.start();
            } else {
                generateWindow.visible = true;
                generateWindow.statusText = "Task failed";
                generateWindow.hideWindow(5000);
            }
        }

        function updateJobStatus() {
            switch(generateJob.jobStatus) {
            case Enums.JobStatusFailed:
                generateWindow.statusText = "Task failed";
                generateWindow.hideWindow(5000);
                break;
            case Enums.JobStatusNotStarted:
                generateWindow.statusText = "Job not started";
                break;
            case Enums.JobStatusPaused:
                generateWindow.statusText = "Job paused";
                break;
            case Enums.JobStatusStarted:
                generateWindow.statusText = "In progress";
                break;
            case Enums.JobStatusSucceeded:
                // show any layer errors
                if (generateJob.result.hasErrors) {
                    const layerErrors = generateJob.result.layerErrors;
                    let errorText = "";
                    for (let i = 0; i < layerErrors.length; i++) {
                        const errorPair = layerErrors[i];
                        errorText += errorPair.layer.name + ": " + errorPair.error.message + "\n";
                    }
                    msgDialog.detailedText = errorText;
                    msgDialog.open();
                }

                // show the map
                generateWindow.statusText = "Complete";
                generateWindow.hideWindow(1500);
                displayOfflineMap(generateJob.result);
                break;
            default:
                console.log("default");
                break;
            }
        }

        function updateProgress() {
            generateWindow.progressText = generateJob.progress;
        }

        function displayOfflineMap(result) {
            // Set the offline map to the MapView
            mapView.map = result.offlineMap;
            downloadButton.visible = false;
            extentRectangle.visible = false;
        }

        Component.onDestruction: {
            if (generateJob) {
                generateJob.jobStatusChanged.disconnect(updateJobStatus);
                generateJob.progressChanged.disconnect(updateProgress);
            }
        }
    }

    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.tpk'.\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;
                    extentRectangle.getRectangleEnvelope();
                    dialog.close();
                }
            }

            Button {
                anchors.horizontalCenter: parent.horizontalCenter
                text: "Download Basemap"
                onClicked: {
                    useLocalBasemap = false;
                    extentRectangle.getRectangleEnvelope();
                    dialog.close();
                }
            }

            Button {
                anchors.horizontalCenter: parent.horizontalCenter
                text: "Cancel"
                onClicked: dialog.close()
            }
        }
    }

    /* Uncomment this section when running as standalone application
    AuthenticationView {
        anchors.fill: parent
        authenticationManager: AuthenticationManager
    }
    */
}
// 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 2.5

// Create the download button to export the tile cache
Rectangle {
    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();
        }
    }
}
// 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 2.6
import QtQuick.Controls 2.2
import QtGraphicalEffects 1.0

Rectangle {
    id: exportWindow
    color: "transparent"
    visible: false
    clip: true

    property string statusText: ""
    property string progressText: ""

    RadialGradient {
        anchors.fill: parent
        opacity: 0.7
        gradient: Gradient {
            GradientStop { position: 0.0; color: "lightgrey" }
            GradientStop { position: 0.7; color: "black" }
        }
    }

    MouseArea {
        anchors.fill: parent
        onClicked: mouse.accepted = true
        onWheel: 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();
    }
}