Learn how to download and display an offline map

Offline maps
In this tutorial, you will download an offline map
Prerequisites
Before starting this tutorial, you need the following:
-
An ArcGIS Location Platform or ArcGIS Online account.
-
A development and deployment environment that meets the system requirements.
-
An IDE for Android development in Kotlin.
Develop or download
You have two options for completing this tutorial:
Option 1: Develop the code
Open an Android Studio project
-
Open the project you created by completing the Display a map tutorial.
-
Continue with the following instructions to download and display an offline map for a user-defined geographical area of a web map.
-
Modify the old project for use in this new tutorial.
-
On your file system, delete the .idea folder, if present, at the top level of your project.
-
In the Android view, open app > res > values > strings.xml.
In the
<string name="app_name">element, change the text content to Display an offline map (on-demand).strings.xml<resources><string name="app_name">Display an offline map (on-demand)</string></resources> -
In the Android view, open Gradle Scripts > settings.gradle.kts.
Change the value of
rootProject.nameto “Display an offline map (on-demand)”.settings.gradle.kts14 collapsed linespluginManagement {repositories {google {content {includeGroupByRegex("com\\.android.*")includeGroupByRegex("com\\.google.*")includeGroupByRegex("androidx.*")}}mavenCentral()gradlePluginPortal()}}dependencyResolutionManagement {repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)repositories {google()mavenCentral()maven { url = uri("https://esri.jfrog.io/artifactory/arcgis") }}}rootProject.name = "Display an offline map (on-demand)"include(":app") -
Click File > Sync Project with Gradle files. Android Studio will recognize your changes and create a new .idea folder.
-
Add import statements and some Compose variables
-
In the Android view, open app > kotlin+java > com.example.app > screens > MainScreen.kt. Replace the import statements with the imports needed for this tutorial.
MainScreen.kt@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar -
In the
MainScreencomposable, create two variables:contextto hold the local context of your app andcoroutineScopeto which you assignrememberCoroutineScope(). Change themapdeclaration tovarrather thanval. You will be assigning the downloaded offline map to themapvariable later in this tutorial.MainScreen.kt@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()var map = remember {createMap()}Scaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,)}}
Get the web map item ID
You can use ArcGIS tools
- Go to the Naperville water network
in the Map Viewer
Map Viewer is a browser-based mapping tool that can view, create, and save web maps. It can also perform mapping, visualization, and spatial analysis operations. in ArcGIS OnlineArcGIS Online is a GIS mapping, analytics, data hosting, and content management software as a service (SaaS) product. It includes applications, tools, APIs, and location services for users and developers. It is subscription-based and requires an ArcGIS Online account. . This web mapA web map is a map stored as a JSON object that defines properties such as the basemap layer, data layers, layer styles, and pop-up styles. Its JSON structure is defined by the web map specification. displays stormwater network within Naperville, IL, USA . - Make a note of the item ID
An item ID is a unique identifier representing a single item stored, managed, and accessed in a portal, such as a web map, hosted layer, or file. at the end of the browser’s URL. The item ID should be:acc027394bc84c2fb04d1ed317aac674
Define a progress bar
-
In
MainScreen, add two variables used in displaying a progress bar.Add a
remembervariable namedcurrentProgress. Inside theremember, callmutableIntStateOf(0). The remembered value is an integer indicating the percent completion of an ongoing operation.Then add a
remembervariable namedshowProgressBar. Inside therememberblock, callmutableStateOf(false). The remembered value is Boolean indicating whether the progress bar is currently visible or not.MainScreen.kt@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }var map = remember {createMap()}Scaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,)}} -
Inside the
Scaffoldblock, find theMapViewfrom the Display a map tutorial and replace it with a call of theColumncomposable.A
Columnallows you to display the progress bar at the top of the screen and the map view below it. Inside theColumnblock, add aLinearProgressIndicatorand then add back theMapViewcode.MainScreen.ktScaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,)}}
Display the web map
You can display a web map
-
In MainScreen.kt, delete the code inside
createMap().Create a
Portalpointing to ArcGIS Online. Then create aPortalItemfor the Naperville water network, using the portal and the web map’s item IDAn item ID is a unique identifier representing a single item stored, managed, and accessed in a portal, such as a web map, hosted layer, or file. . Then return the map.MainScreen.kt136 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }val offlineArea = remember {createAreaOfInterest(onOfflineAreaCreated = { graphic -> graphicsOverlay.graphics.add(graphic) })}var map = remember {createMap()}LaunchedEffect(Unit) {// Create an offline map task using the current mapval offlineMapTask = OfflineMapTask(map)// Create a default set of parameters for generating the offline map from the area of interestofflineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea).onSuccess { parameters ->// When the parameters are successfully created, show progress bar and messageshowProgressBar.value = trueshowMessage(context, "Default parameters have been created.")// Download the offline mapdownloadOfflineMapArea(context = context,coroutineScope = coroutineScope,offlineMapTask = offlineMapTask,parameters = parameters,updateProgress = { currentProgress.intValue = it },onDownloadOfflineMapSuccess = { offlineMap ->// Hide progress bar and show message when the job executes successfullyshowProgressBar.value = falseshowMessage(context, "Downloaded offline map area successfully.")// Replace the current map with the result offline mapmap = offlineMap// Clear the offline area outlinegraphicsOverlay.graphics.clear()},onDownloadOfflineMapFailure = {showProgressBar.value = falseshowMessage(context, "Failed to download offline map area.")})}}Scaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}fun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}78 collapsed linesfun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}suspend fun downloadOfflineMapArea(context: Context,coroutineScope: CoroutineScope,offlineMapTask: OfflineMapTask,parameters: GenerateOfflineMapParameters,updateProgress: (Int) -> Unit,onDownloadOfflineMapSuccess: (ArcGISMap) -> Unit,onDownloadOfflineMapFailure: () -> Unit) {// Build a folder path named with today's date/time to store the offline mapval downloadLocation =context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time// Create a job with GenerateOfflineMapParameters and a download directory pathval generateOfflineMapJob = offlineMapTask.createGenerateOfflineMapJob(parameters = parameters,downloadDirectoryPath = downloadLocation)coroutineScope.launch {generateOfflineMapJob.progress.collect { progress ->updateProgress(progress)}}// Start the job to download the offline mapgenerateOfflineMapJob.start()showMessage( context, "Generate offline map job has started.")generateOfflineMapJob.result().onSuccess { generateOfflineMapResult ->onDownloadOfflineMapSuccess(generateOfflineMapResult.offlineMap)}.onFailure {onDownloadOfflineMapFailure()}}fun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()} -
Click Run > Run > app to run the app.
You should see a map of the stormwater network within Naperville, IL, USA . Tap and hold to drag, scroll, and double-tap the map view to explore the map.
Specify an area of the web map to take offline
You can specify an area of the web mapEnvelope to specify the geometry of the offline area and a transparent symbol with red outline to visually identify the area on the screen.
-
Create a graphic from an offline map area and a red-outline symbol.
-
Create a function named
createAreaOfInterest()that takes a lambda as parameter and returns anEnvelope. The type of the lambda takes aGraphicand returns nothing. -
Create an
Envelopewith maximum and minimum coordinates in the center of Naperville, IL, and assign it to a variable namedofflineArea. -
Create a
SimpleLineSymbolwith a red solid line. Then create a transparentSimpleFillSymbolusing the solid red line. Last, create aGraphicusing the offline area and the fill symbol. -
Use the
onOfflineAreaCreatedparameter to invoke the lambda, passing in theofflineAreaGraphicyou created. Then returnofflineArea.MainScreen.kt111 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }val offlineArea = remember {createAreaOfInterest(onOfflineAreaCreated = { graphic -> graphicsOverlay.graphics.add(graphic) })}var map = remember {createMap()}Scaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}fun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}fun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}4 collapsed linesfun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()}
-
-
Near the top of the
MainScreencomposable, create aremembervariable namedgraphicsOverlay. Inside therememberblock, instantiateGraphicsOverlay.Then create a
remembervariable namedgraphicsOverlays. Inside therememberblock, create a list that contains one item:graphicsOverlay.Last, pass
graphicsOverlaysto the map view.MainScreen.kt44 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }var map = remember {createMap()}Scaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}54 collapsed linesfun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}fun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}fun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()} -
Create a
remembervariable namedofflineArea. Set it by calling thecreateAreaOfInterest()function you just created and passing a lambda as theonOfflineAreaCreatedparameter. Your lambda takes aGraphicand adds it to the graphics overlay.Consult the
createAreaOfInterest()function to see the code that invokes the lambda and passes theofflineAreaGraphic.MainScreen.kt111 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }val offlineArea = remember {createAreaOfInterest(onOfflineAreaCreated = { graphic -> graphicsOverlay.graphics.add(graphic) })}var map = remember {createMap()}Scaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}fun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}fun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}4 collapsed linesfun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()}MainScreen.kt44 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }val offlineArea = remember {createAreaOfInterest(onOfflineAreaCreated = { graphic -> graphicsOverlay.graphics.add(graphic) })}89 collapsed linesvar map = remember {createMap()}Scaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}fun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}fun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}fun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()} -
Click Run > Run > app to run the app.
You should see a red outline on the stormwater network within Naperville, IL, USA . This indicates the area of the web map that you are going to take offline.
Download an offline map area
The workflow for downloading an offline map
- Create an offline map task, passing in the web map.
- Create a default set of parameters to be used for downloading an offline map area. (Use the offline map task.)
- Create a job for downloading the offline map area. (Use the offline map task and pass the default parameters.)
- Start the job.
- Display the offline map area.
For the sake of this tutorial, we will first define a function named downloadOfflineMapArea(), which will take OfflineMapTask and GenerateOfflineMapParameters (and other values) and download the offline map area. Then we will go to the MainScreen block, create OfflineMapTask and GenerateOfflineMapParameters objects, and call downloadOfflineMapArea() with the appropriate values.
Define downloadOfflineMapArea()
-
Create a top-level
suspendfunction nameddownloadOfflineMapArea(). Declare the parameters indicated in the code below.MainScreen.kt186 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }val offlineArea = remember {createAreaOfInterest(onOfflineAreaCreated = { graphic -> graphicsOverlay.graphics.add(graphic) })}var map = remember {createMap()}LaunchedEffect(Unit) {// Create an offline map task using the current mapval offlineMapTask = OfflineMapTask(map)// Create a default set of parameters for generating the offline map from the area of interestofflineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea).onSuccess { parameters ->// When the parameters are successfully created, show progress bar and messageshowProgressBar.value = trueshowMessage(context, "Default parameters have been created.")// Download the offline mapdownloadOfflineMapArea(context = context,coroutineScope = coroutineScope,offlineMapTask = offlineMapTask,parameters = parameters,updateProgress = { currentProgress.intValue = it },onDownloadOfflineMapSuccess = { offlineMap ->// Hide progress bar and show message when the job executes successfullyshowProgressBar.value = falseshowMessage(context, "Downloaded offline map area successfully.")// Replace the current map with the result offline mapmap = offlineMap// Clear the offline area outlinegraphicsOverlay.graphics.clear()},onDownloadOfflineMapFailure = {showProgressBar.value = falseshowMessage(context, "Failed to download offline map area.")})}}Scaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}fun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}fun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}suspend fun downloadOfflineMapArea(context: Context,coroutineScope: CoroutineScope,offlineMapTask: OfflineMapTask,parameters: GenerateOfflineMapParameters,updateProgress: (Int) -> Unit,onDownloadOfflineMapSuccess: (ArcGISMap) -> Unit,onDownloadOfflineMapFailure: () -> Unit) {}4 collapsed linesfun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()} -
Create a variable named
downloadLocation, which holds the path on the device system where offline map area will be downloaded. The path is a string.MainScreen.kt186 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }val offlineArea = remember {createAreaOfInterest(onOfflineAreaCreated = { graphic -> graphicsOverlay.graphics.add(graphic) })}var map = remember {createMap()}LaunchedEffect(Unit) {// Create an offline map task using the current mapval offlineMapTask = OfflineMapTask(map)// Create a default set of parameters for generating the offline map from the area of interestofflineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea).onSuccess { parameters ->// When the parameters are successfully created, show progress bar and messageshowProgressBar.value = trueshowMessage(context, "Default parameters have been created.")// Download the offline mapdownloadOfflineMapArea(context = context,coroutineScope = coroutineScope,offlineMapTask = offlineMapTask,parameters = parameters,updateProgress = { currentProgress.intValue = it },onDownloadOfflineMapSuccess = { offlineMap ->// Hide progress bar and show message when the job executes successfullyshowProgressBar.value = falseshowMessage(context, "Downloaded offline map area successfully.")// Replace the current map with the result offline mapmap = offlineMap// Clear the offline area outlinegraphicsOverlay.graphics.clear()},onDownloadOfflineMapFailure = {showProgressBar.value = falseshowMessage(context, "Failed to download offline map area.")})}}Scaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}fun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}fun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}suspend fun downloadOfflineMapArea(context: Context,coroutineScope: CoroutineScope,offlineMapTask: OfflineMapTask,parameters: GenerateOfflineMapParameters,updateProgress: (Int) -> Unit,onDownloadOfflineMapSuccess: (ArcGISMap) -> Unit,onDownloadOfflineMapFailure: () -> Unit) {// Build a folder path named with today's date/time to store the offline mapval downloadLocation =context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time}4 collapsed linesfun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()} -
Create a job that will generate the offline map area. To do this, call
OfflineMapTask.createGenerateOfflineMapJob()and pass the default parameters and thedownloadLocation.MainScreen.kt186 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }val offlineArea = remember {createAreaOfInterest(onOfflineAreaCreated = { graphic -> graphicsOverlay.graphics.add(graphic) })}var map = remember {createMap()}LaunchedEffect(Unit) {// Create an offline map task using the current mapval offlineMapTask = OfflineMapTask(map)// Create a default set of parameters for generating the offline map from the area of interestofflineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea).onSuccess { parameters ->// When the parameters are successfully created, show progress bar and messageshowProgressBar.value = trueshowMessage(context, "Default parameters have been created.")// Download the offline mapdownloadOfflineMapArea(context = context,coroutineScope = coroutineScope,offlineMapTask = offlineMapTask,parameters = parameters,updateProgress = { currentProgress.intValue = it },onDownloadOfflineMapSuccess = { offlineMap ->// Hide progress bar and show message when the job executes successfullyshowProgressBar.value = falseshowMessage(context, "Downloaded offline map area successfully.")// Replace the current map with the result offline mapmap = offlineMap// Clear the offline area outlinegraphicsOverlay.graphics.clear()},onDownloadOfflineMapFailure = {showProgressBar.value = falseshowMessage(context, "Failed to download offline map area.")})}}Scaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}fun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}fun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}suspend fun downloadOfflineMapArea(context: Context,coroutineScope: CoroutineScope,offlineMapTask: OfflineMapTask,parameters: GenerateOfflineMapParameters,updateProgress: (Int) -> Unit,onDownloadOfflineMapSuccess: (ArcGISMap) -> Unit,onDownloadOfflineMapFailure: () -> Unit) {// Build a folder path named with today's date/time to store the offline mapval downloadLocation =context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time// Create a job with GenerateOfflineMapParameters and a download directory pathval generateOfflineMapJob = offlineMapTask.createGenerateOfflineMapJob(parameters = parameters,downloadDirectoryPath = downloadLocation)}4 collapsed linesfun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()} -
Update the progress of the generate offline map job.
MainScreen.kt186 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }val offlineArea = remember {createAreaOfInterest(onOfflineAreaCreated = { graphic -> graphicsOverlay.graphics.add(graphic) })}var map = remember {createMap()}LaunchedEffect(Unit) {// Create an offline map task using the current mapval offlineMapTask = OfflineMapTask(map)// Create a default set of parameters for generating the offline map from the area of interestofflineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea).onSuccess { parameters ->// When the parameters are successfully created, show progress bar and messageshowProgressBar.value = trueshowMessage(context, "Default parameters have been created.")// Download the offline mapdownloadOfflineMapArea(context = context,coroutineScope = coroutineScope,offlineMapTask = offlineMapTask,parameters = parameters,updateProgress = { currentProgress.intValue = it },onDownloadOfflineMapSuccess = { offlineMap ->// Hide progress bar and show message when the job executes successfullyshowProgressBar.value = falseshowMessage(context, "Downloaded offline map area successfully.")// Replace the current map with the result offline mapmap = offlineMap// Clear the offline area outlinegraphicsOverlay.graphics.clear()},onDownloadOfflineMapFailure = {showProgressBar.value = falseshowMessage(context, "Failed to download offline map area.")})}}Scaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}fun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}fun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}suspend fun downloadOfflineMapArea(context: Context,coroutineScope: CoroutineScope,offlineMapTask: OfflineMapTask,parameters: GenerateOfflineMapParameters,updateProgress: (Int) -> Unit,onDownloadOfflineMapSuccess: (ArcGISMap) -> Unit,onDownloadOfflineMapFailure: () -> Unit) {// Build a folder path named with today's date/time to store the offline mapval downloadLocation =context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time// Create a job with GenerateOfflineMapParameters and a download directory pathval generateOfflineMapJob = offlineMapTask.createGenerateOfflineMapJob(parameters = parameters,downloadDirectoryPath = downloadLocation)coroutineScope.launch {generateOfflineMapJob.progress.collect { progress ->updateProgress(progress)}}}4 collapsed linesfun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()} -
Start the generate offline map job.
MainScreen.kt186 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }val offlineArea = remember {createAreaOfInterest(onOfflineAreaCreated = { graphic -> graphicsOverlay.graphics.add(graphic) })}var map = remember {createMap()}LaunchedEffect(Unit) {// Create an offline map task using the current mapval offlineMapTask = OfflineMapTask(map)// Create a default set of parameters for generating the offline map from the area of interestofflineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea).onSuccess { parameters ->// When the parameters are successfully created, show progress bar and messageshowProgressBar.value = trueshowMessage(context, "Default parameters have been created.")// Download the offline mapdownloadOfflineMapArea(context = context,coroutineScope = coroutineScope,offlineMapTask = offlineMapTask,parameters = parameters,updateProgress = { currentProgress.intValue = it },onDownloadOfflineMapSuccess = { offlineMap ->// Hide progress bar and show message when the job executes successfullyshowProgressBar.value = falseshowMessage(context, "Downloaded offline map area successfully.")// Replace the current map with the result offline mapmap = offlineMap// Clear the offline area outlinegraphicsOverlay.graphics.clear()},onDownloadOfflineMapFailure = {showProgressBar.value = falseshowMessage(context, "Failed to download offline map area.")})}}Scaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}fun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}fun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}suspend fun downloadOfflineMapArea(context: Context,coroutineScope: CoroutineScope,offlineMapTask: OfflineMapTask,parameters: GenerateOfflineMapParameters,updateProgress: (Int) -> Unit,onDownloadOfflineMapSuccess: (ArcGISMap) -> Unit,onDownloadOfflineMapFailure: () -> Unit) {// Build a folder path named with today's date/time to store the offline mapval downloadLocation =context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time// Create a job with GenerateOfflineMapParameters and a download directory pathval generateOfflineMapJob = offlineMapTask.createGenerateOfflineMapJob(parameters = parameters,downloadDirectoryPath = downloadLocation)coroutineScope.launch {generateOfflineMapJob.progress.collect { progress ->updateProgress(progress)}}// Start the job to download the offline mapgenerateOfflineMapJob.start()showMessage( context, "Generate offline map job has started.")}4 collapsed linesfun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()} -
Respond to the result of the generate offline map job.
Among the parameters passed to
downloadOfflineMapArea(), two are particularly important here:onDownloadOfflineMapSuccessonDownloadOfflineMapFailure
Both parameters are of function type (lambda).
In the
onSuccessblock, invoke theonDownloadOfflineMapSuccess()lambda, passing the offline map from the generate offline map result. In theonFailureblock, invoke theonDownloadOfflineMapFailure()lambda.MainScreen.kt186 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }val offlineArea = remember {createAreaOfInterest(onOfflineAreaCreated = { graphic -> graphicsOverlay.graphics.add(graphic) })}var map = remember {createMap()}LaunchedEffect(Unit) {// Create an offline map task using the current mapval offlineMapTask = OfflineMapTask(map)// Create a default set of parameters for generating the offline map from the area of interestofflineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea).onSuccess { parameters ->// When the parameters are successfully created, show progress bar and messageshowProgressBar.value = trueshowMessage(context, "Default parameters have been created.")// Download the offline mapdownloadOfflineMapArea(context = context,coroutineScope = coroutineScope,offlineMapTask = offlineMapTask,parameters = parameters,updateProgress = { currentProgress.intValue = it },onDownloadOfflineMapSuccess = { offlineMap ->// Hide progress bar and show message when the job executes successfullyshowProgressBar.value = falseshowMessage(context, "Downloaded offline map area successfully.")// Replace the current map with the result offline mapmap = offlineMap// Clear the offline area outlinegraphicsOverlay.graphics.clear()},onDownloadOfflineMapFailure = {showProgressBar.value = falseshowMessage(context, "Failed to download offline map area.")})}}Scaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}fun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}fun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}suspend fun downloadOfflineMapArea(context: Context,coroutineScope: CoroutineScope,offlineMapTask: OfflineMapTask,parameters: GenerateOfflineMapParameters,updateProgress: (Int) -> Unit,onDownloadOfflineMapSuccess: (ArcGISMap) -> Unit,onDownloadOfflineMapFailure: () -> Unit) {// Build a folder path named with today's date/time to store the offline mapval downloadLocation =context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time// Create a job with GenerateOfflineMapParameters and a download directory pathval generateOfflineMapJob = offlineMapTask.createGenerateOfflineMapJob(parameters = parameters,downloadDirectoryPath = downloadLocation)coroutineScope.launch {generateOfflineMapJob.progress.collect { progress ->updateProgress(progress)}}// Start the job to download the offline mapgenerateOfflineMapJob.start()showMessage( context, "Generate offline map job has started.")generateOfflineMapJob.result().onSuccess { generateOfflineMapResult ->onDownloadOfflineMapSuccess(generateOfflineMapResult.offlineMap)}.onFailure {onDownloadOfflineMapFailure()}}4 collapsed linesfun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()}
Call downloadOfflineMapArea()
-
In the
MainScreencomposable, after themapvariable: add theLaunchedEffectcomposable. Then create anOfflineMapTask, passingmap.MainScreen.kt47 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }val offlineArea = remember {createAreaOfInterest(onOfflineAreaCreated = { graphic -> graphicsOverlay.graphics.add(graphic) })}var map = remember {createMap()}LaunchedEffect(Unit) {// Create an offline map task using the current mapval offlineMapTask = OfflineMapTask(map)}84 collapsed linesScaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}fun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}fun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}fun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()} -
You will now create a default set of parameters for generating an offline map area on the server and and downloading the area.
Call
OfflineMapTask.createDefaultGenerateOfflineMapParameters(), passing the offline map area. Then create anonSuccessblock to handle the successful creation of the default parameters.MainScreen.kt47 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }val offlineArea = remember {createAreaOfInterest(onOfflineAreaCreated = { graphic -> graphicsOverlay.graphics.add(graphic) })}var map = remember {createMap()}LaunchedEffect(Unit) {// Create an offline map task using the current mapval offlineMapTask = OfflineMapTask(map)// Create a default set of parameters for generating the offline map from the area of interestofflineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea).onSuccess { parameters ->}}84 collapsed linesScaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}fun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}fun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}fun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()} -
In the
onSuccessblock, set the value ofshowProgressBarand show a message saying that the default parameters have been created.MainScreen.kt47 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }val offlineArea = remember {createAreaOfInterest(onOfflineAreaCreated = { graphic -> graphicsOverlay.graphics.add(graphic) })}var map = remember {createMap()}LaunchedEffect(Unit) {// Create an offline map task using the current mapval offlineMapTask = OfflineMapTask(map)// Create a default set of parameters for generating the offline map from the area of interestofflineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea).onSuccess { parameters ->// When the parameters are successfully created, show progress bar and messageshowProgressBar.value = trueshowMessage(context, "Default parameters have been created.")}}84 collapsed linesScaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}fun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}fun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}fun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()} -
Continuing in the
onSuccessblock, calldownloadOfflineMapArea()function, passing theofflineMapTaskand the defaultparameters. Also pass a lambda foronDownloadOfflineMapSuccessand a lambda foronDownloadOfflineMapFailure.The
onDownloadOfflineMapSuccesslambda hides the progress bar and displays a message saying the offline map area downloaded successfully. Then it assigns the lambda’sofflineMapparameter to themapvariable, which displays the offline map in the map view. Last, the lambda clears the red outline around the offline map area.The
onDownloadOfflineMapFailurelambda hides the progress bar and displays a message saying the offline map area failed to download.MainScreen.kt47 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }val offlineArea = remember {createAreaOfInterest(onOfflineAreaCreated = { graphic -> graphicsOverlay.graphics.add(graphic) })}var map = remember {createMap()}LaunchedEffect(Unit) {// Create an offline map task using the current mapval offlineMapTask = OfflineMapTask(map)// Create a default set of parameters for generating the offline map from the area of interestofflineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea).onSuccess { parameters ->// When the parameters are successfully created, show progress bar and messageshowProgressBar.value = trueshowMessage(context, "Default parameters have been created.")// Download the offline mapdownloadOfflineMapArea(context = context,coroutineScope = coroutineScope,offlineMapTask = offlineMapTask,parameters = parameters,updateProgress = { currentProgress.intValue = it },onDownloadOfflineMapSuccess = { offlineMap ->// Hide progress bar and show message when the job executes successfullyshowProgressBar.value = falseshowMessage(context, "Downloaded offline map area successfully.")// Replace the current map with the result offline mapmap = offlineMap// Clear the offline area outlinegraphicsOverlay.graphics.clear()},onDownloadOfflineMapFailure = {showProgressBar.value = falseshowMessage(context, "Failed to download offline map area.")})}}122 collapsed linesScaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}fun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}fun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}suspend fun downloadOfflineMapArea(context: Context,coroutineScope: CoroutineScope,offlineMapTask: OfflineMapTask,parameters: GenerateOfflineMapParameters,updateProgress: (Int) -> Unit,onDownloadOfflineMapSuccess: (ArcGISMap) -> Unit,onDownloadOfflineMapFailure: () -> Unit) {// Build a folder path named with today's date/time to store the offline mapval downloadLocation =context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time// Create a job with GenerateOfflineMapParameters and a download directory pathval generateOfflineMapJob = offlineMapTask.createGenerateOfflineMapJob(parameters = parameters,downloadDirectoryPath = downloadLocation)coroutineScope.launch {generateOfflineMapJob.progress.collect { progress ->updateProgress(progress)}}// Start the job to download the offline mapgenerateOfflineMapJob.start()showMessage( context, "Generate offline map job has started.")generateOfflineMapJob.result().onSuccess { generateOfflineMapResult ->onDownloadOfflineMapSuccess(generateOfflineMapResult.offlineMap)}.onFailure {onDownloadOfflineMapFailure()}}fun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()} -
(Optional) The code in this tutorial calls a function to display messages to the user. One possible implementation of
showMessage()is the following.MainScreen.kt224 collapsed lines@file:OptIn(ExperimentalMaterial3Api::class)package com.example.app.screensimport android.content.Contextimport android.widget.Toastimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TopAppBarimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.stringResourceimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.SpatialReferenceimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.example.app.Rimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.util.Calendar@Composablefun MainScreen() {val context = LocalContext.currentval coroutineScope = rememberCoroutineScope()val currentProgress = remember { mutableIntStateOf(0) }val showProgressBar = remember { mutableStateOf(false) }val graphicsOverlay = remember { GraphicsOverlay() }val graphicsOverlays = remember { listOf(graphicsOverlay) }val offlineArea = remember {createAreaOfInterest(onOfflineAreaCreated = { graphic -> graphicsOverlay.graphics.add(graphic) })}var map = remember {createMap()}LaunchedEffect(Unit) {// Create an offline map task using the current mapval offlineMapTask = OfflineMapTask(map)// Create a default set of parameters for generating the offline map from the area of interestofflineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea).onSuccess { parameters ->// When the parameters are successfully created, show progress bar and messageshowProgressBar.value = trueshowMessage(context, "Default parameters have been created.")// Download the offline mapdownloadOfflineMapArea(context = context,coroutineScope = coroutineScope,offlineMapTask = offlineMapTask,parameters = parameters,updateProgress = { currentProgress.intValue = it },onDownloadOfflineMapSuccess = { offlineMap ->// Hide progress bar and show message when the job executes successfullyshowProgressBar.value = falseshowMessage(context, "Downloaded offline map area successfully.")// Replace the current map with the result offline mapmap = offlineMap// Clear the offline area outlinegraphicsOverlay.graphics.clear()},onDownloadOfflineMapFailure = {showProgressBar.value = falseshowMessage(context, "Failed to download offline map area.")})}}Scaffold(topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.app_name)) }) }) {Column(modifier = Modifier.fillMaxSize().padding(it)) {if (showProgressBar.value) {LinearProgressIndicator(progress = {currentProgress.intValue / 100f},modifier = Modifier.fillMaxWidth(),)}MapView(modifier = Modifier.fillMaxSize(),arcGISMap = map,graphicsOverlays = graphicsOverlays)}}}fun createMap(): ArcGISMap {val portal = Portal(url = "https://www.arcgis.com",connection = Portal.Connection.Anonymous)val portalItem = PortalItem(portal = portal,itemId = "acc027394bc84c2fb04d1ed317aac674")return ArcGISMap(portalItem)}fun createAreaOfInterest(onOfflineAreaCreated: (Graphic) -> Unit): Envelope {// Create an envelope that defines the area to take offlineval offlineArea = Envelope(xMin = -88.1526,yMin = 41.7694,xMax = -88.1490,yMax = 41.7714,spatialReference = SpatialReference.wgs84())// Create a graphic to display the area to take offlineval lineSymbol = SimpleLineSymbol(style = SimpleLineSymbolStyle.Solid,color = Color.red,width = 2f)val fillSymbol = SimpleFillSymbol(style = SimpleFillSymbolStyle.Solid,color = Color.transparent,outline = lineSymbol)val offlineAreaGraphic = Graphic(geometry = offlineArea,symbol = fillSymbol)// Add the offline area outline to the graphics overlayonOfflineAreaCreated(offlineAreaGraphic)return offlineArea}suspend fun downloadOfflineMapArea(context: Context,coroutineScope: CoroutineScope,offlineMapTask: OfflineMapTask,parameters: GenerateOfflineMapParameters,updateProgress: (Int) -> Unit,onDownloadOfflineMapSuccess: (ArcGISMap) -> Unit,onDownloadOfflineMapFailure: () -> Unit) {// Build a folder path named with today's date/time to store the offline mapval downloadLocation =context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time// Create a job with GenerateOfflineMapParameters and a download directory pathval generateOfflineMapJob = offlineMapTask.createGenerateOfflineMapJob(parameters = parameters,downloadDirectoryPath = downloadLocation)coroutineScope.launch {generateOfflineMapJob.progress.collect { progress ->updateProgress(progress)}}// Start the job to download the offline mapgenerateOfflineMapJob.start()showMessage( context, "Generate offline map job has started.")generateOfflineMapJob.result().onSuccess { generateOfflineMapResult ->onDownloadOfflineMapSuccess(generateOfflineMapResult.offlineMap)}.onFailure {onDownloadOfflineMapFailure()}}fun showMessage(context: Context, message: String) {Toast.makeText(context, message, Toast.LENGTH_LONG).show()} -
Click Run > Run > app to run the app.
Initially, you should see the web map centered on Naperville, IL, USA, with a red outline indicating the area that will be taken offline. The download starts automatically, and the progress bar displays at the top of the screen as a dark-blue line, expanding to the right as progress is made. The download might take from a few seconds to a minute or more, depending on your internet connection.
After the offline map
An offline map is a map area and its data content downloaded from an offline-enabled web map for use in offline applications built with ArcGIS Maps SDKs for Native Apps. area is downloaded to the Android device, you should see the offline map area, surrounded by a gray grid. You can now remove your network connection, and you will still be able to use the mouse to drag, scroll, and double-click the map view to explore this offline map area.
Alternatively, you can download the tutorial solution, as follows.
Option 2: Download the solution
-
Click the Download solution link in the right-hand side of this page.
-
Unzip the file to a location on your machine.
-
Run Android Studio.
-
Go to File > Open…. Navigate to the solution folder and click Open.
On Windows: If you are in the Welcome to Android Studio dialog, click Open and navigate to the solution folder. Then click Open.
Since the downloaded solution does not contain authentication credentials, you must first set up authentication to create credentials, and then add the developer credentials to the solution.
Set up authentication
To access the secure ArcGIS location services
You can implement API key authentication or user authentication in this tutorial. Compare the differences below:
API key authentication
- Users are not required to sign in.
- Requires creating an API key credential
API key credentials are an item that contains the parameters used to create and manage long-lived access tokens for API key authentication. They are a type of developer credential. with the correct privileges. - API keys
An API key is a long-lived access token created using API key credentials. They are valid for up to one year and are typically embedded directly into client applications. are long-lived access tokens. - Service usage is billed to the API key owner/developer.
- Simplest authentication method to implement.
- Recommended approach for new ArcGIS developers.
Learn more in API key authentication.
User authentication
- Users are required to sign in with an ArcGIS account
An ArcGIS account is an identity with a user type and set of privileges that can access specific ArcGIS products, tools, APIs, services, and resources. The main account types that can be used for development are an ArcGIS Location Platform account, ArcGIS Online account, and ArcGIS Enterprise account. ArcGIS Location Platform and ArcGIS Online accounts are also associated with a subscription. . - User accounts must have privilege
Privileges are a set of permissions assigned to ArcGIS accounts, developer credentials, and applications that grant access to secure resources and functionality in ArcGIS. to access the ArcGIS servicesA service, also known as an ArcGIS service, is software that supports an ArcGIS REST API and provides geospatial functionality or data. A service can be hosted by Esri or in ArcGIS Enterprise. used in application. - Requires creating OAuth credentials
OAuth credentials are an item that contains parameters required to implement user authentication or app authentication, including a .client_id,client_secret, and redirect URIs. They are a type of developer credential. - Application uses a redirect URL and client ID.
- Service usage is billed to the organization of the user signed into the application.
Learn more in User authentication.
To complete this tutorial, click on the tab in the switcher below for your authentication type of choice, either API key authentication or User authentication.
Create a new API key access token
-
Complete the Create an API key tutorial and create an API key with the following privilege(s)
Privileges are a set of permissions assigned to ArcGIS accounts, developer credentials, and applications that grant access to secure resources and functionality in ArcGIS. :- Privileges
- Location services > Basemaps
- Privileges
-
Copy and paste the API key access token into a safe location. It will be used in a later step.
Create new OAuth credentials to access the secure resources used in this tutorial.
-
Complete the Create OAuth credentials for user authentication tutorial to obtain a Client ID and Redirect URL.
A
Client IDuniquely identifies your app on the authenticating server. If the server cannot find an app with the provided Client ID, it will not proceed with authentication.The
Redirect URL(also referred to as a callback url) is used to identify a response from the authenticating server when the system returns control back to your app after an OAuth login. Since it does not necessarily represent a valid endpoint that a user could navigate to, the redirect URL can use a custom scheme, such asmy-app://auth. It is important to make sure the redirect URL used in your app’s code matches a redirect URL configured on the authenticating server. -
Copy and paste the Client ID and Redirect URL into a safe location. They will be used in a later step.
All users that access this application need account privileges
Set developer credentials in the solution
To allow your app users to access ArcGIS location services
-
In the Android view of Android Studio, open app > kotlin+java > com.example.app > MainActivity. Set the
AuthenticationModeto.API_KEY.MainActivity.kt14 collapsed linespackage com.example.appimport android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport com.arcgismaps.ApiKeyimport com.arcgismaps.ArcGISEnvironmentimport com.arcgismaps.httpcore.authentication.OAuthUserConfigurationimport com.arcgismaps.toolkit.authentication.AuthenticatorStateimport com.arcgismaps.toolkit.authentication.DialogAuthenticatorimport com.example.app.screens.MainScreenimport com.example.app.ui.theme.TutorialThemeclass MainActivity : ComponentActivity() {private enum class AuthenticationMode { API_KEY, USER_AUTH }private val authenticationMode = AuthenticationMode.API_KEY42 collapsed linesprivate val authenticatorState = AuthenticatorState()override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)when (authenticationMode) {AuthenticationMode.API_KEY -> {ArcGISEnvironment.apiKey = ApiKey.create("YOUR_ACCESS_TOKEN")}AuthenticationMode.USER_AUTH -> {authenticatorState.oAuthUserConfigurations = listOf(OAuthUserConfiguration(portalUrl = "https://www.arcgis.com",clientId = "YOUR_CLIENT_ID",redirectUrl = "YOUR_REDIRECT_URL"))}}enableEdgeToEdge()setContent {TutorialTheme {MainScreen()if (authenticationMode == AuthenticationMode.USER_AUTH) {DialogAuthenticator(authenticatorState)}}}}} -
Set the
apiKeyproperty with your API key access token.MainActivity.kt22 collapsed linespackage com.example.appimport android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport com.arcgismaps.ApiKeyimport com.arcgismaps.ArcGISEnvironmentimport com.arcgismaps.httpcore.authentication.OAuthUserConfigurationimport com.arcgismaps.toolkit.authentication.AuthenticatorStateimport com.arcgismaps.toolkit.authentication.DialogAuthenticatorimport com.example.app.screens.MainScreenimport com.example.app.ui.theme.TutorialThemeclass MainActivity : ComponentActivity() {private enum class AuthenticationMode { API_KEY, USER_AUTH }private val authenticationMode = AuthenticationMode.API_KEYprivate val authenticatorState = AuthenticatorState()override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)when (authenticationMode) {AuthenticationMode.API_KEY -> {ArcGISEnvironment.apiKey = ApiKey.create("YOUR_ACCESS_TOKEN")}30 collapsed linesAuthenticationMode.USER_AUTH -> {authenticatorState.oAuthUserConfigurations = listOf(OAuthUserConfiguration(portalUrl = "https://www.arcgis.com",clientId = "YOUR_CLIENT_ID",redirectUrl = "YOUR_REDIRECT_URL"))}}enableEdgeToEdge()setContent {TutorialTheme {MainScreen()if (authenticationMode == AuthenticationMode.USER_AUTH) {DialogAuthenticator(authenticatorState)}}}}}
Best Practice: The access token is stored directly in the code as a convenience for this tutorial. Do not store credentials directly in source code in a production environment.
-
In the Android view of Android Studio, open app > kotlin+java > com.example.app > MainActivity. Set the
AuthenticationModeto.USER_AUTH.MainActivity.ktclass MainActivity : ComponentActivity() {private enum class AuthenticationMode { API_KEY, USER_AUTH }private val authenticationMode = AuthenticationMode.USER_AUTH -
Set your
clientIDandredirectURLvalues. You must use the RedirectURL that you supplied for your app in theuser authenticationpart of the Set up authentication step.MainActivity.ktAuthenticationMode.USER_AUTH -> {authenticatorState.oAuthUserConfigurations = listOf(OAuthUserConfiguration(portalUrl = "https://www.arcgis.com",clientId = "YOUR_CLIENT_ID",redirectUrl = "YOUR_REDIRECT_URL")) -
Open app > manifests > AndroidManifest.xml.
-
Set the
android:schemeandandroid:hostusing the scheme and host from your RedirectURL.A redirectURL is composed of a scheme and a host component. The format for the redirect url is
scheme://host. For example, if the redirect url ismyscheme://myhostthen the scheme ismyschemeand the host ismyhost.AndroidManifest.xml41 collapsed lines<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"><uses-permission android:name="android.permission.INTERNET" /><applicationandroid:allowBackup="true"android:dataExtractionRules="@xml/data_extraction_rules"android:fullBackupContent="@xml/backup_rules"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/Theme.Tutorial"tools:targetApi="31"><activityandroid:name=".MainActivity"android:exported="true"android:label="@string/app_name"android:theme="@style/Theme.Tutorial"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><activityandroid:name="com.arcgismaps.toolkit.authentication.AuthenticationActivity"android:configChanges="keyboard|keyboardHidden|orientation|screenSize"android:exported="true"android:launchMode="singleTop" ><intent-filter><action android:name="android.intent.action.VIEW" /><category android:name="android.intent.category.DEFAULT" /><category android:name="android.intent.category.BROWSABLE" /><dataandroid:scheme="your_redirect_url_scheme"android:host="your_redirect_url_host" />6 collapsed lines</intent-filter></activity></application></manifest>
Best Practice: The OAuth credentials are stored directly in the code as a convenience for this tutorial. Do not store credentials directly in source code in a production environment.
Run the app
Click Run > Run > app to run the app.
Initially, you should see the web map centered on Naperville, IL, USA, with a red outline indicating the area that will be taken offline. The download starts automatically, and the progress bar displays at the top of the screen as a dark-blue line, expanding to the right as progress is made. The download might take from a few seconds to a minute or more, depending on your internet connection.
After the offline map
What’s next?
Learn how to use additional API features, ArcGIS location services, and ArcGIS tools in these tutorials: