Take a web map offline with additional options for each layer.
Use case
When taking a web map offline, you may adjust the data (such as layers or tiles) that is downloaded by using custom parameter overrides. This can be used to reduce the extent of the map or the download size of the offline map. It can also be used to highlight specific data by removing irrelevant data. Additionally, this workflow allows you to take features offline that don't have a geometry - for example, features whose attributes have been populated in the office, but still need a site survey for their geometry.
How to use the sample
Modify the overrides parameters:
- Use the min/max scale input fields to adjust the level IDs to be taken offline for the streets basemap.
- Use the extent buffer distance input field to set the buffer radius for the streets basemap.
- Check the checkboxes for the feature operational layers you want to include in the offline map.
- Use the min hydrant flow rate input field to only download features with a flow rate higher than this value.
- Select the "Water Pipes" checkbox if you want to crop the water pipe features to the extent of the map.
After you have set up the overrides to your liking, tap the "Generate offline map" button to start the download. A progress bar will display. Tap the "Cancel" button if you want to stop the download. When the download is complete, the view will display the offline map. Pan around to see that it is cropped to the download area's extent.
How it works
- Load a web map from a
PortalItem
. Authenticate with the portal if required. - Create an
OfflineMapTask
with the map. - Generate default task parameters using the extent area you want to download with
offlineMapTask.CreateDefaultGenerateOfflineMapParametersAsync(extent)
. - Generate additional "override" parameters using the default parameters with
offlineMapTask.CreateGenerateOfflineMapParameterOverridesAsync(parameters)
. - For the basemap:
- Get the parameters
OfflineMapParametersKey
for the basemap layer. - Get the
ExportTileCacheParameters
for the basemap layer withoverrides.ExportTileCacheParameters[basemapParamKey]
. - Set the level IDs you want to download with
exportTileCacheParametersLevelIDs().Add(levelID)
. - To buffer the extent, set the
exportTileCacheParameters.AreaOfInterest
property. B uffered geometry can be calculated with theGeometryEngine
.
- Get the parameters
- To remove operational layers from the download:
- Create a
OfflineParametersKey
with the operational layer. - Get the generate geodatabase layer options using the key with
List<GenerateLayerOption> layerOptions = overrides.GenerateGeodatabaseParameters[key].LayerOptions;
- Loop through each
GenerateLayerOption
in the the list, and remove it if the layer option's ID matches the layer's ID.
- Create a
- To filter the features downloaded in an operational layer:
- Get the layer options for the operational layer using the directions in step 6.
- Loop through the layer options. If the option
LayerID
matches the layer's ID, set the filter clause withlayerOption.WhereClause
property and set the query option withlayerOption.QueryOption
property.
- To not crop a layer's features to the extent of the offline map (default is true):
- Set the
layerOption.UseGeometry
property tofalse
.
- Set the
- Create a
GenerateOfflineMapJob
withofflineMapTask.GenerateOfflineMap(parameters, downloadPath, overrides)
. - Get a reference to the offline map with
job.GetResultAsync()
Relevant API
- ExportTileCacheParameters
- GenerateGeodatabaseParameters
- GenerateLayerOption
- GenerateOfflineMapJob
- GenerateOfflineMapParameterOverrides
- GenerateOfflineMapParameters
- GenerateOfflineMapResult
- OfflineMapParametersKey
- OfflineMapTask
Additional information
For applications where you just need to take all layers offline, use the standard workflow (using only GenerateOfflineMapParameters
). For a simple example of how you take a map offline, please consult the "Generate offline map" sample.
Tags
adjust, download, extent, filter, LOD, offline, override, parameters, reduce, scale range, setting
Sample Code
// Copyright 2021 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.
using Android.App;
using Android.OS;
using Android.Widget;
using ArcGISRuntime.Samples.GenerateOfflineMapWithOverrides;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks;
using Esri.ArcGISRuntime.Tasks.Offline;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AlertDialog = Android.App.AlertDialog;
namespace ArcGISRuntimeXamarin.Samples.GenerateOfflineMapWithOverrides
{
[Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Generate offline map (overrides)",
category: "Map",
description: "Take a web map offline with additional options for each layer.",
instructions: "Modify the overrides parameters:",
tags: new[] { "LOD", "adjust", "download", "extent", "filter", "offline", "override", "parameters", "reduce", "scale range", "setting" })]
public class GenerateOfflineMapWithOverrides : Activity
{
// Mapview.
private MapView _mapView;
// Generate Button.
private Button _takeMapOfflineButton;
// Progress indicator.
private AlertDialog _alertDialog;
private ProgressBar _progressIndicator;
// The job to generate an offline map.
private GenerateOfflineMapJob _generateOfflineMapJob;
// The extent of the data to take offline.
private Envelope _areaOfInterest = new Envelope(-88.1541, 41.7690, -88.1471, 41.7720, SpatialReferences.Wgs84);
// The ID for a web map item hosted on the server (water network map of Naperville IL).
private const string WebMapId = "acc027394bc84c2fb04d1ed317aac674";
// Values for taking things the map offline.
private string _packagePath;
private OfflineMapTask _takeMapOfflineTask;
private GenerateOfflineMapParameters _parameters;
private GenerateOfflineMapParameterOverrides _overrides;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "Generate offline map (overrides)";
// Create the UI, setup the control references and execute initialization.
CreateLayout();
Initialize();
}
private void CreateLayout()
{
// Create the layout.
LinearLayout layout = new LinearLayout(this)
{
Orientation = Orientation.Vertical
};
// Add the generate button.
_takeMapOfflineButton = new Button(this)
{
Text = "Take map offline"
};
_takeMapOfflineButton.Click += TakeMapOfflineButton_Click;
layout.AddView(_takeMapOfflineButton);
// Add the mapview.
_mapView = new MapView(this);
layout.AddView(_mapView);
// Add the layout to the view.
SetContentView(layout);
// Create the progress dialog display.
_progressIndicator = new ProgressBar(this);
_progressIndicator.SetProgress(40, true);
AlertDialog.Builder builder = new AlertDialog.Builder(this).SetView(_progressIndicator);
builder.SetCancelable(true);
builder.SetMessage("Generating offline map ...");
_alertDialog = builder.Create();
_alertDialog.SetButton("Cancel", (s, e) => { _generateOfflineMapJob.CancelAsync(); });
}
private async void Initialize()
{
try
{
// Create the ArcGIS Online portal.
ArcGISPortal portal = await ArcGISPortal.CreateAsync();
// Get the Naperville water web map item using its ID.
PortalItem webmapItem = await PortalItem.CreateAsync(portal, WebMapId);
// Create a map from the web map item.
Map onlineMap = new Map(webmapItem);
// Display the map in the MapView.
_mapView.Map = onlineMap;
// Disable user interactions on the map (no panning or zooming from the initial extent).
_mapView.InteractionOptions = new MapViewInteractionOptions
{
IsEnabled = false
};
// Create a graphics overlay for the extent graphic and apply a renderer.
SimpleLineSymbol aoiOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Red, 3);
GraphicsOverlay extentOverlay = new GraphicsOverlay
{
Renderer = new SimpleRenderer(aoiOutlineSymbol)
};
_mapView.GraphicsOverlays.Add(extentOverlay);
// Add a graphic to show the area of interest (extent) that will be taken offline.
Graphic aoiGraphic = new Graphic(_areaOfInterest);
extentOverlay.Graphics.Add(aoiGraphic);
}
catch (Exception ex)
{
// Show the exception message to the user.
ShowStatusMessage(ex.Message);
}
}
private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
{
// Create a path for the output mobile map.
string tempPath = $"{Path.GetTempPath()}";
string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");
// Loop through the folder names and delete them.
foreach (string dir in outputFolders)
{
try
{
// Delete the folder.
Directory.Delete(dir, true);
}
catch (Exception)
{
// Ignore exceptions (files might be locked, for example).
}
}
// Create a new folder for the output mobile map.
_packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork");
int num = 1;
while (Directory.Exists(_packagePath))
{
_packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num.ToString());
num++;
}
// Create the output directory.
Directory.CreateDirectory(_packagePath);
try
{
// Create an offline map task with the current (online) map.
_takeMapOfflineTask = await OfflineMapTask.CreateAsync(_mapView.Map);
// Create the default parameters for the task, pass in the area of interest.
_parameters = await _takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);
// Get the overrides.
_overrides = await _takeMapOfflineTask.CreateGenerateOfflineMapParameterOverridesAsync(_parameters);
// Create the overrides UI.
ParameterOverrideFragment overlayFragment = new ParameterOverrideFragment(_overrides, _mapView.Map);
// Complete configuration when the dialog is closed.
overlayFragment.FinishedConfiguring += ConfigurationContinuation;
// Display the configuration window.
overlayFragment.Show(FragmentManager, "");
}
catch (Exception ex)
{
// Exception while taking the map offline.
ShowStatusMessage(ex.Message);
}
}
private async void ConfigurationContinuation(object sender, EventArgs e)
{
try
{
// Show the progress dialog while the job is running.
_alertDialog.Show();
// Create the job with the parameters and output location.
_generateOfflineMapJob = _takeMapOfflineTask.GenerateOfflineMap(_parameters, _packagePath, _overrides);
// Handle the progress changed event for the job.
_generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;
// Await the job to generate geodatabases, export tile packages, and create the mobile map package.
GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();
// Check for job failure (writing the output was denied, e.g.).
if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
{
// Report failure to the user.
ShowStatusMessage("Failed to take the map offline.");
}
// Check for errors with individual layers.
if (results.LayerErrors.Any())
{
// Build a string to show all layer errors.
System.Text.StringBuilder errorBuilder = new System.Text.StringBuilder();
foreach (KeyValuePair<Layer, Exception> layerError in results.LayerErrors)
{
errorBuilder.AppendLine($"{layerError.Key.Id} : {layerError.Value.Message}");
}
// Show layer errors.
ShowStatusMessage(errorBuilder.ToString());
}
// Display the offline map.
_mapView.Map = results.OfflineMap;
// Apply the original viewpoint for the offline map.
_mapView.SetViewpoint(new Viewpoint(_areaOfInterest));
// Enable map interaction so the user can explore the offline data.
_mapView.InteractionOptions.IsEnabled = true;
// Change the title and disable the "Take map offline" button.
_takeMapOfflineButton.Text = "Map is offline";
_takeMapOfflineButton.Enabled = false;
}
catch (TaskCanceledException)
{
// Generate offline map task was canceled.
ShowStatusMessage("Taking map offline was canceled");
}
catch (Exception ex)
{
// Exception while taking the map offline.
ShowStatusMessage(ex.Message);
}
finally
{
_alertDialog.Dismiss();
}
}
private void ShowStatusMessage(string message)
{
// Display the message to the user.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.SetMessage(message).SetTitle("Alert").Show();
}
// Show changes in job progress.
private void OfflineMapJob_ProgressChanged(object sender, EventArgs e)
{
// Get the job.
GenerateOfflineMapJob job = sender as GenerateOfflineMapJob;
// Dispatch to the UI thread.
RunOnUiThread(() =>
{
// Show the percent complete and update the progress bar.
string percentText = job.Progress > 0 ? job.Progress.ToString() + " %" : string.Empty;
_progressIndicator.Progress = job.Progress;
_alertDialog.SetMessage($"Taking map offline ({percentText}) ...");
});
}
}
}