Learn how to download and display an 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. Learn more for a user-defined geographical area of a web map A 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. Learn more .

display an offline map custom

Offline maps 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. Learn more allow users to continue working when network connectivity is poor or lost. If a web map A 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. Learn more is enabled for offline use, a user can request that ArcGIS generates an offline map for a specified geographic area of interest.

In this tutorial, you will download an 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. Learn more for an area of interest from the web map A 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. Learn more of the stormwater network within Naperville, IL, USA . You can then use this offline map without a network connection.

Prerequisites

Before starting this tutorial, you need the following:

  1. An ArcGIS Location Platform or ArcGIS Online account.

  2. A development and deployment environment that meets the system requirements.

  3. An IDE for Android development in Kotlin.

Develop or download

You have two options for completing this tutorial:

  1. Option 1: Develop the code or
  2. Option 2: Download the completed solution

Option 1: Develop the code

Open an Android Studio project

  1. Open the project you created by completing the Display a map tutorial.

  2. Continue with the following instructions to download and display an offline map for a user-defined geographical area of a web map.

  3. Modify the old project for use in this new tutorial.

Add import statements and some Compose variables

  1. 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.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.LinearProgressIndicator
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.mutableIntStateOf
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.Color
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.geometry.SpatialReference
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.PortalItem
    import com.arcgismaps.mapping.symbology.SimpleFillSymbol
    import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
    import com.arcgismaps.mapping.symbology.SimpleLineSymbol
    import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
    import com.arcgismaps.mapping.view.Graphic
    import com.arcgismaps.mapping.view.GraphicsOverlay
    import com.arcgismaps.portal.Portal
    import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
    import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.launch
    import java.util.Calendar
  2. In the MainScreen composable, create two variables: context to hold the local context of your app and coroutineScope to which you assign rememberCoroutineScope(). Change the map declaration to var rather than val. You will be assigning the downloaded offline map to the map variable later in this tutorial.

    MainScreen.kt
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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 Tools, also known as developer tools, are ArcGIS software applications such as portal and ArcGIS Pro that developers can use to prepare content and data for custom applications they are building. Learn more to create and view web maps A 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. Learn more . Use 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. Learn more to identify the web map 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. Learn more . This item ID will be used later in the tutorial.

  1. 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. Learn more in ArcGIS Online ArcGIS 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. Learn more . This web map A 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. Learn more displays stormwater network within Naperville, IL, USA .
  2. 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. Learn more at the end of the browser’s URL. The item ID should be:

    acc027394bc84c2fb04d1ed317aac674

Define a progress bar

  1. In MainScreen, add two variables used in displaying a progress bar.

    Add a remember variable named currentProgress. Inside the remember, call mutableIntStateOf(0). The remembered value is an integer indicating the percent completion of an ongoing operation.

    Then add a remember variable named showProgressBar. Inside the remember block, call mutableStateOf(false). The remembered value is Boolean indicating whether the progress bar is currently visible or not.

    MainScreen.kt
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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,
    )
    }
    }
  2. Inside the Scaffold block, find the MapView from the Display a map tutorial and replace it with a call of the Column composable.

    A Column allows you to display the progress bar at the top of the screen and the map view below it. Inside the Column block, add a LinearProgressIndicator and then add back the MapView code.

    MainScreen.kt
    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,
    )
    }
    }

Display the web map

You can display a web map A 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. Learn more using the web map’s 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. Learn more . Create a map A map is a collection of layers that are displayed in 2D. It is typically composed of a basemap layer and data layers. Learn more from the web map portal item An item, also known as a content item, is a resource stored in a portal such as a web map, hosted layer, style, script tool, file, or notebook. Learn more , and display it in your app.

  1. In MainScreen.kt, delete the code inside createMap().

    Create a Portal pointing to ArcGIS Online. Then create a PortalItem for the Naperville water network, using the portal and the web map’s 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. Learn more . Then return the map.

    MainScreen.kt
    136 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.LinearProgressIndicator
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.mutableIntStateOf
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.Color
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.geometry.SpatialReference
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.PortalItem
    import com.arcgismaps.mapping.symbology.SimpleFillSymbol
    import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
    import com.arcgismaps.mapping.symbology.SimpleLineSymbol
    import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
    import com.arcgismaps.mapping.view.Graphic
    import com.arcgismaps.mapping.view.GraphicsOverlay
    import com.arcgismaps.portal.Portal
    import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
    import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.launch
    import java.util.Calendar
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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 map
    val offlineMapTask = OfflineMapTask(map)
    // Create a default set of parameters for generating the offline map from the area of interest
    offlineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea)
    .onSuccess { parameters ->
    // When the parameters are successfully created, show progress bar and message
    showProgressBar.value = true
    showMessage(context, "Default parameters have been created.")
    // Download the offline map
    downloadOfflineMapArea(
    context = context,
    coroutineScope = coroutineScope,
    offlineMapTask = offlineMapTask,
    parameters = parameters,
    updateProgress = { currentProgress.intValue = it },
    onDownloadOfflineMapSuccess = { offlineMap ->
    // Hide progress bar and show message when the job executes successfully
    showProgressBar.value = false
    showMessage(context, "Downloaded offline map area successfully.")
    // Replace the current map with the result offline map
    map = offlineMap
    // Clear the offline area outline
    graphicsOverlay.graphics.clear()
    },
    onDownloadOfflineMapFailure = {
    showProgressBar.value = false
    showMessage(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 lines
    fun createAreaOfInterest(
    onOfflineAreaCreated: (Graphic) -> Unit
    ): Envelope {
    // Create an envelope that defines the area to take offline
    val 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 offline
    val 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 overlay
    onOfflineAreaCreated(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 map
    val downloadLocation =
    context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time
    // Create a job with GenerateOfflineMapParameters and a download directory path
    val generateOfflineMapJob = offlineMapTask.createGenerateOfflineMapJob(
    parameters = parameters,
    downloadDirectoryPath = downloadLocation
    )
    coroutineScope.launch {
    generateOfflineMapJob.progress.collect { progress ->
    updateProgress(progress)
    }
    }
    // Start the job to download the offline map
    generateOfflineMapJob.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()
    }
  2. 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 map A 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. Learn more that you want to be taken offline. Use an Envelope to specify the geometry of the offline area and a transparent symbol with red outline to visually identify the area on the screen.

  1. Create a graphic from an offline map area and a red-outline symbol.

    1. Create a function named createAreaOfInterest() that takes a lambda as parameter and returns an Envelope. The type of the lambda takes a Graphic and returns nothing.

    2. Create an Envelope with maximum and minimum coordinates in the center of Naperville, IL, and assign it to a variable named offlineArea.

    3. Create a SimpleLineSymbol with a red solid line. Then create a transparent SimpleFillSymbol using the solid red line. Last, create a Graphic using the offline area and the fill symbol.

    4. Use the onOfflineAreaCreated parameter to invoke the lambda, passing in the offlineAreaGraphic you created. Then return offlineArea.

      MainScreen.kt
      111 collapsed lines
      @file:OptIn(ExperimentalMaterial3Api::class)
      package com.example.app.screens
      import android.content.Context
      import android.widget.Toast
      import androidx.compose.foundation.layout.Column
      import androidx.compose.foundation.layout.fillMaxSize
      import androidx.compose.foundation.layout.fillMaxWidth
      import androidx.compose.foundation.layout.padding
      import androidx.compose.material3.ExperimentalMaterial3Api
      import androidx.compose.material3.LinearProgressIndicator
      import androidx.compose.material3.Scaffold
      import androidx.compose.material3.Text
      import androidx.compose.material3.TopAppBar
      import androidx.compose.runtime.Composable
      import androidx.compose.runtime.LaunchedEffect
      import androidx.compose.runtime.mutableIntStateOf
      import androidx.compose.runtime.mutableStateOf
      import androidx.compose.runtime.remember
      import androidx.compose.runtime.rememberCoroutineScope
      import androidx.compose.ui.Modifier
      import androidx.compose.ui.platform.LocalContext
      import androidx.compose.ui.res.stringResource
      import com.arcgismaps.Color
      import com.arcgismaps.geometry.Envelope
      import com.arcgismaps.geometry.SpatialReference
      import com.arcgismaps.mapping.ArcGISMap
      import com.arcgismaps.mapping.PortalItem
      import com.arcgismaps.mapping.symbology.SimpleFillSymbol
      import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
      import com.arcgismaps.mapping.symbology.SimpleLineSymbol
      import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
      import com.arcgismaps.mapping.view.Graphic
      import com.arcgismaps.mapping.view.GraphicsOverlay
      import com.arcgismaps.portal.Portal
      import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
      import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
      import com.arcgismaps.toolkit.geoviewcompose.MapView
      import com.example.app.R
      import kotlinx.coroutines.CoroutineScope
      import kotlinx.coroutines.launch
      import java.util.Calendar
      @Composable
      fun MainScreen() {
      val context = LocalContext.current
      val 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 offline
      val 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 offline
      val 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 overlay
      onOfflineAreaCreated(offlineAreaGraphic)
      return offlineArea
      }
      4 collapsed lines
      fun showMessage(context: Context, message: String) {
      Toast.makeText(context, message, Toast.LENGTH_LONG).show()
      }
  2. Near the top of the MainScreen composable, create a remember variable named graphicsOverlay. Inside the remember block, instantiate GraphicsOverlay.

    Then create a remember variable named graphicsOverlays. Inside the remember block, create a list that contains one item: graphicsOverlay.

    Last, pass graphicsOverlays to the map view.

    MainScreen.kt
    44 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.LinearProgressIndicator
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.mutableIntStateOf
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.Color
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.geometry.SpatialReference
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.PortalItem
    import com.arcgismaps.mapping.symbology.SimpleFillSymbol
    import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
    import com.arcgismaps.mapping.symbology.SimpleLineSymbol
    import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
    import com.arcgismaps.mapping.view.Graphic
    import com.arcgismaps.mapping.view.GraphicsOverlay
    import com.arcgismaps.portal.Portal
    import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
    import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.launch
    import java.util.Calendar
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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 lines
    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 offline
    val 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 offline
    val 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 overlay
    onOfflineAreaCreated(offlineAreaGraphic)
    return offlineArea
    }
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  3. Create a remember variable named offlineArea. Set it by calling the createAreaOfInterest() function you just created and passing a lambda as the onOfflineAreaCreated parameter. Your lambda takes a Graphic and adds it to the graphics overlay.

    MainScreen.kt
    44 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.LinearProgressIndicator
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.mutableIntStateOf
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.Color
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.geometry.SpatialReference
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.PortalItem
    import com.arcgismaps.mapping.symbology.SimpleFillSymbol
    import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
    import com.arcgismaps.mapping.symbology.SimpleLineSymbol
    import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
    import com.arcgismaps.mapping.view.Graphic
    import com.arcgismaps.mapping.view.GraphicsOverlay
    import com.arcgismaps.portal.Portal
    import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
    import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.launch
    import java.util.Calendar
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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 lines
    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 offline
    val 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 offline
    val 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 overlay
    onOfflineAreaCreated(offlineAreaGraphic)
    return offlineArea
    }
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  4. 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 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. Learn more area from the server to the Android device is as follows:

  • 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()

  1. Create a top-level suspend function named downloadOfflineMapArea(). Declare the parameters indicated in the code below.

    MainScreen.kt
    186 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.LinearProgressIndicator
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.mutableIntStateOf
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.Color
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.geometry.SpatialReference
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.PortalItem
    import com.arcgismaps.mapping.symbology.SimpleFillSymbol
    import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
    import com.arcgismaps.mapping.symbology.SimpleLineSymbol
    import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
    import com.arcgismaps.mapping.view.Graphic
    import com.arcgismaps.mapping.view.GraphicsOverlay
    import com.arcgismaps.portal.Portal
    import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
    import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.launch
    import java.util.Calendar
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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 map
    val offlineMapTask = OfflineMapTask(map)
    // Create a default set of parameters for generating the offline map from the area of interest
    offlineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea)
    .onSuccess { parameters ->
    // When the parameters are successfully created, show progress bar and message
    showProgressBar.value = true
    showMessage(context, "Default parameters have been created.")
    // Download the offline map
    downloadOfflineMapArea(
    context = context,
    coroutineScope = coroutineScope,
    offlineMapTask = offlineMapTask,
    parameters = parameters,
    updateProgress = { currentProgress.intValue = it },
    onDownloadOfflineMapSuccess = { offlineMap ->
    // Hide progress bar and show message when the job executes successfully
    showProgressBar.value = false
    showMessage(context, "Downloaded offline map area successfully.")
    // Replace the current map with the result offline map
    map = offlineMap
    // Clear the offline area outline
    graphicsOverlay.graphics.clear()
    },
    onDownloadOfflineMapFailure = {
    showProgressBar.value = false
    showMessage(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 offline
    val 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 offline
    val 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 overlay
    onOfflineAreaCreated(offlineAreaGraphic)
    return offlineArea
    }
    suspend fun downloadOfflineMapArea(
    context: Context,
    coroutineScope: CoroutineScope,
    offlineMapTask: OfflineMapTask,
    parameters: GenerateOfflineMapParameters,
    updateProgress: (Int) -> Unit,
    onDownloadOfflineMapSuccess: (ArcGISMap) -> Unit,
    onDownloadOfflineMapFailure: () -> Unit
    ) {
    }
    4 collapsed lines
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  2. 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.kt
    186 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.LinearProgressIndicator
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.mutableIntStateOf
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.Color
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.geometry.SpatialReference
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.PortalItem
    import com.arcgismaps.mapping.symbology.SimpleFillSymbol
    import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
    import com.arcgismaps.mapping.symbology.SimpleLineSymbol
    import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
    import com.arcgismaps.mapping.view.Graphic
    import com.arcgismaps.mapping.view.GraphicsOverlay
    import com.arcgismaps.portal.Portal
    import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
    import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.launch
    import java.util.Calendar
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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 map
    val offlineMapTask = OfflineMapTask(map)
    // Create a default set of parameters for generating the offline map from the area of interest
    offlineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea)
    .onSuccess { parameters ->
    // When the parameters are successfully created, show progress bar and message
    showProgressBar.value = true
    showMessage(context, "Default parameters have been created.")
    // Download the offline map
    downloadOfflineMapArea(
    context = context,
    coroutineScope = coroutineScope,
    offlineMapTask = offlineMapTask,
    parameters = parameters,
    updateProgress = { currentProgress.intValue = it },
    onDownloadOfflineMapSuccess = { offlineMap ->
    // Hide progress bar and show message when the job executes successfully
    showProgressBar.value = false
    showMessage(context, "Downloaded offline map area successfully.")
    // Replace the current map with the result offline map
    map = offlineMap
    // Clear the offline area outline
    graphicsOverlay.graphics.clear()
    },
    onDownloadOfflineMapFailure = {
    showProgressBar.value = false
    showMessage(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 offline
    val 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 offline
    val 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 overlay
    onOfflineAreaCreated(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 map
    val downloadLocation =
    context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time
    }
    4 collapsed lines
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  3. Create a job that will generate the offline map area. To do this, call OfflineMapTask.createGenerateOfflineMapJob() and pass the default parameters and the downloadLocation.

    MainScreen.kt
    186 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.LinearProgressIndicator
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.mutableIntStateOf
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.Color
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.geometry.SpatialReference
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.PortalItem
    import com.arcgismaps.mapping.symbology.SimpleFillSymbol
    import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
    import com.arcgismaps.mapping.symbology.SimpleLineSymbol
    import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
    import com.arcgismaps.mapping.view.Graphic
    import com.arcgismaps.mapping.view.GraphicsOverlay
    import com.arcgismaps.portal.Portal
    import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
    import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.launch
    import java.util.Calendar
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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 map
    val offlineMapTask = OfflineMapTask(map)
    // Create a default set of parameters for generating the offline map from the area of interest
    offlineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea)
    .onSuccess { parameters ->
    // When the parameters are successfully created, show progress bar and message
    showProgressBar.value = true
    showMessage(context, "Default parameters have been created.")
    // Download the offline map
    downloadOfflineMapArea(
    context = context,
    coroutineScope = coroutineScope,
    offlineMapTask = offlineMapTask,
    parameters = parameters,
    updateProgress = { currentProgress.intValue = it },
    onDownloadOfflineMapSuccess = { offlineMap ->
    // Hide progress bar and show message when the job executes successfully
    showProgressBar.value = false
    showMessage(context, "Downloaded offline map area successfully.")
    // Replace the current map with the result offline map
    map = offlineMap
    // Clear the offline area outline
    graphicsOverlay.graphics.clear()
    },
    onDownloadOfflineMapFailure = {
    showProgressBar.value = false
    showMessage(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 offline
    val 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 offline
    val 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 overlay
    onOfflineAreaCreated(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 map
    val downloadLocation =
    context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time
    // Create a job with GenerateOfflineMapParameters and a download directory path
    val generateOfflineMapJob = offlineMapTask.createGenerateOfflineMapJob(
    parameters = parameters,
    downloadDirectoryPath = downloadLocation
    )
    }
    4 collapsed lines
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  4. Update the progress of the generate offline map job.

    MainScreen.kt
    186 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.LinearProgressIndicator
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.mutableIntStateOf
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.Color
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.geometry.SpatialReference
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.PortalItem
    import com.arcgismaps.mapping.symbology.SimpleFillSymbol
    import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
    import com.arcgismaps.mapping.symbology.SimpleLineSymbol
    import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
    import com.arcgismaps.mapping.view.Graphic
    import com.arcgismaps.mapping.view.GraphicsOverlay
    import com.arcgismaps.portal.Portal
    import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
    import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.launch
    import java.util.Calendar
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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 map
    val offlineMapTask = OfflineMapTask(map)
    // Create a default set of parameters for generating the offline map from the area of interest
    offlineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea)
    .onSuccess { parameters ->
    // When the parameters are successfully created, show progress bar and message
    showProgressBar.value = true
    showMessage(context, "Default parameters have been created.")
    // Download the offline map
    downloadOfflineMapArea(
    context = context,
    coroutineScope = coroutineScope,
    offlineMapTask = offlineMapTask,
    parameters = parameters,
    updateProgress = { currentProgress.intValue = it },
    onDownloadOfflineMapSuccess = { offlineMap ->
    // Hide progress bar and show message when the job executes successfully
    showProgressBar.value = false
    showMessage(context, "Downloaded offline map area successfully.")
    // Replace the current map with the result offline map
    map = offlineMap
    // Clear the offline area outline
    graphicsOverlay.graphics.clear()
    },
    onDownloadOfflineMapFailure = {
    showProgressBar.value = false
    showMessage(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 offline
    val 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 offline
    val 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 overlay
    onOfflineAreaCreated(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 map
    val downloadLocation =
    context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time
    // Create a job with GenerateOfflineMapParameters and a download directory path
    val generateOfflineMapJob = offlineMapTask.createGenerateOfflineMapJob(
    parameters = parameters,
    downloadDirectoryPath = downloadLocation
    )
    coroutineScope.launch {
    generateOfflineMapJob.progress.collect { progress ->
    updateProgress(progress)
    }
    }
    }
    4 collapsed lines
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  5. Start the generate offline map job.

    MainScreen.kt
    186 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.LinearProgressIndicator
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.mutableIntStateOf
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.Color
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.geometry.SpatialReference
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.PortalItem
    import com.arcgismaps.mapping.symbology.SimpleFillSymbol
    import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
    import com.arcgismaps.mapping.symbology.SimpleLineSymbol
    import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
    import com.arcgismaps.mapping.view.Graphic
    import com.arcgismaps.mapping.view.GraphicsOverlay
    import com.arcgismaps.portal.Portal
    import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
    import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.launch
    import java.util.Calendar
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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 map
    val offlineMapTask = OfflineMapTask(map)
    // Create a default set of parameters for generating the offline map from the area of interest
    offlineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea)
    .onSuccess { parameters ->
    // When the parameters are successfully created, show progress bar and message
    showProgressBar.value = true
    showMessage(context, "Default parameters have been created.")
    // Download the offline map
    downloadOfflineMapArea(
    context = context,
    coroutineScope = coroutineScope,
    offlineMapTask = offlineMapTask,
    parameters = parameters,
    updateProgress = { currentProgress.intValue = it },
    onDownloadOfflineMapSuccess = { offlineMap ->
    // Hide progress bar and show message when the job executes successfully
    showProgressBar.value = false
    showMessage(context, "Downloaded offline map area successfully.")
    // Replace the current map with the result offline map
    map = offlineMap
    // Clear the offline area outline
    graphicsOverlay.graphics.clear()
    },
    onDownloadOfflineMapFailure = {
    showProgressBar.value = false
    showMessage(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 offline
    val 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 offline
    val 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 overlay
    onOfflineAreaCreated(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 map
    val downloadLocation =
    context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time
    // Create a job with GenerateOfflineMapParameters and a download directory path
    val generateOfflineMapJob = offlineMapTask.createGenerateOfflineMapJob(
    parameters = parameters,
    downloadDirectoryPath = downloadLocation
    )
    coroutineScope.launch {
    generateOfflineMapJob.progress.collect { progress ->
    updateProgress(progress)
    }
    }
    // Start the job to download the offline map
    generateOfflineMapJob.start()
    showMessage( context, "Generate offline map job has started.")
    }
    4 collapsed lines
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  6. Respond to the result of the generate offline map job.

    Among the parameters passed to downloadOfflineMapArea(), two are particularly important here:

    • onDownloadOfflineMapSuccess
    • onDownloadOfflineMapFailure

    Both parameters are of function type (lambda).

    In the onSuccess block, invoke the onDownloadOfflineMapSuccess() lambda, passing the offline map from the generate offline map result. In the onFailure block, invoke the onDownloadOfflineMapFailure() lambda.

    MainScreen.kt
    186 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.LinearProgressIndicator
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.mutableIntStateOf
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.Color
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.geometry.SpatialReference
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.PortalItem
    import com.arcgismaps.mapping.symbology.SimpleFillSymbol
    import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
    import com.arcgismaps.mapping.symbology.SimpleLineSymbol
    import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
    import com.arcgismaps.mapping.view.Graphic
    import com.arcgismaps.mapping.view.GraphicsOverlay
    import com.arcgismaps.portal.Portal
    import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
    import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.launch
    import java.util.Calendar
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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 map
    val offlineMapTask = OfflineMapTask(map)
    // Create a default set of parameters for generating the offline map from the area of interest
    offlineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea)
    .onSuccess { parameters ->
    // When the parameters are successfully created, show progress bar and message
    showProgressBar.value = true
    showMessage(context, "Default parameters have been created.")
    // Download the offline map
    downloadOfflineMapArea(
    context = context,
    coroutineScope = coroutineScope,
    offlineMapTask = offlineMapTask,
    parameters = parameters,
    updateProgress = { currentProgress.intValue = it },
    onDownloadOfflineMapSuccess = { offlineMap ->
    // Hide progress bar and show message when the job executes successfully
    showProgressBar.value = false
    showMessage(context, "Downloaded offline map area successfully.")
    // Replace the current map with the result offline map
    map = offlineMap
    // Clear the offline area outline
    graphicsOverlay.graphics.clear()
    },
    onDownloadOfflineMapFailure = {
    showProgressBar.value = false
    showMessage(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 offline
    val 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 offline
    val 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 overlay
    onOfflineAreaCreated(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 map
    val downloadLocation =
    context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time
    // Create a job with GenerateOfflineMapParameters and a download directory path
    val generateOfflineMapJob = offlineMapTask.createGenerateOfflineMapJob(
    parameters = parameters,
    downloadDirectoryPath = downloadLocation
    )
    coroutineScope.launch {
    generateOfflineMapJob.progress.collect { progress ->
    updateProgress(progress)
    }
    }
    // Start the job to download the offline map
    generateOfflineMapJob.start()
    showMessage( context, "Generate offline map job has started.")
    generateOfflineMapJob.result().onSuccess { generateOfflineMapResult ->
    onDownloadOfflineMapSuccess(generateOfflineMapResult.offlineMap)
    }.onFailure {
    onDownloadOfflineMapFailure()
    }
    }
    4 collapsed lines
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }

Call downloadOfflineMapArea()

  1. In the MainScreen composable, after the map variable: add the LaunchedEffect composable. Then create an OfflineMapTask, passing map.

    MainScreen.kt
    47 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.LinearProgressIndicator
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.mutableIntStateOf
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.Color
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.geometry.SpatialReference
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.PortalItem
    import com.arcgismaps.mapping.symbology.SimpleFillSymbol
    import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
    import com.arcgismaps.mapping.symbology.SimpleLineSymbol
    import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
    import com.arcgismaps.mapping.view.Graphic
    import com.arcgismaps.mapping.view.GraphicsOverlay
    import com.arcgismaps.portal.Portal
    import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
    import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.launch
    import java.util.Calendar
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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 map
    val offlineMapTask = OfflineMapTask(map)
    }
    84 collapsed lines
    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 offline
    val 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 offline
    val 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 overlay
    onOfflineAreaCreated(offlineAreaGraphic)
    return offlineArea
    }
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  2. 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 an onSuccess block to handle the successful creation of the default parameters.

    MainScreen.kt
    47 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.LinearProgressIndicator
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.mutableIntStateOf
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.Color
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.geometry.SpatialReference
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.PortalItem
    import com.arcgismaps.mapping.symbology.SimpleFillSymbol
    import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
    import com.arcgismaps.mapping.symbology.SimpleLineSymbol
    import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
    import com.arcgismaps.mapping.view.Graphic
    import com.arcgismaps.mapping.view.GraphicsOverlay
    import com.arcgismaps.portal.Portal
    import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
    import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.launch
    import java.util.Calendar
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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 map
    val offlineMapTask = OfflineMapTask(map)
    // Create a default set of parameters for generating the offline map from the area of interest
    offlineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea)
    .onSuccess { parameters ->
    }
    }
    84 collapsed lines
    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 offline
    val 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 offline
    val 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 overlay
    onOfflineAreaCreated(offlineAreaGraphic)
    return offlineArea
    }
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  3. In the onSuccess block, set the value of showProgressBar and show a message saying that the default parameters have been created.

    MainScreen.kt
    47 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.LinearProgressIndicator
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.mutableIntStateOf
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.Color
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.geometry.SpatialReference
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.PortalItem
    import com.arcgismaps.mapping.symbology.SimpleFillSymbol
    import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
    import com.arcgismaps.mapping.symbology.SimpleLineSymbol
    import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
    import com.arcgismaps.mapping.view.Graphic
    import com.arcgismaps.mapping.view.GraphicsOverlay
    import com.arcgismaps.portal.Portal
    import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
    import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.launch
    import java.util.Calendar
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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 map
    val offlineMapTask = OfflineMapTask(map)
    // Create a default set of parameters for generating the offline map from the area of interest
    offlineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea)
    .onSuccess { parameters ->
    // When the parameters are successfully created, show progress bar and message
    showProgressBar.value = true
    showMessage(context, "Default parameters have been created.")
    }
    }
    84 collapsed lines
    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 offline
    val 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 offline
    val 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 overlay
    onOfflineAreaCreated(offlineAreaGraphic)
    return offlineArea
    }
    fun showMessage(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }
  4. Continuing in the onSuccess block, call downloadOfflineMapArea() function, passing the offlineMapTask and the default parameters. Also pass a lambda for onDownloadOfflineMapSuccess and a lambda for onDownloadOfflineMapFailure.

    MainScreen.kt
    47 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.LinearProgressIndicator
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.mutableIntStateOf
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.Color
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.geometry.SpatialReference
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.PortalItem
    import com.arcgismaps.mapping.symbology.SimpleFillSymbol
    import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
    import com.arcgismaps.mapping.symbology.SimpleLineSymbol
    import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
    import com.arcgismaps.mapping.view.Graphic
    import com.arcgismaps.mapping.view.GraphicsOverlay
    import com.arcgismaps.portal.Portal
    import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
    import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.launch
    import java.util.Calendar
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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 map
    val offlineMapTask = OfflineMapTask(map)
    // Create a default set of parameters for generating the offline map from the area of interest
    offlineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea)
    .onSuccess { parameters ->
    // When the parameters are successfully created, show progress bar and message
    showProgressBar.value = true
    showMessage(context, "Default parameters have been created.")
    // Download the offline map
    downloadOfflineMapArea(
    context = context,
    coroutineScope = coroutineScope,
    offlineMapTask = offlineMapTask,
    parameters = parameters,
    updateProgress = { currentProgress.intValue = it },
    onDownloadOfflineMapSuccess = { offlineMap ->
    // Hide progress bar and show message when the job executes successfully
    showProgressBar.value = false
    showMessage(context, "Downloaded offline map area successfully.")
    // Replace the current map with the result offline map
    map = offlineMap
    // Clear the offline area outline
    graphicsOverlay.graphics.clear()
    },
    onDownloadOfflineMapFailure = {
    showProgressBar.value = false
    showMessage(context, "Failed to download offline map area.")
    }
    )
    }
    }
    122 collapsed lines
    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 offline
    val 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 offline
    val 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 overlay
    onOfflineAreaCreated(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 map
    val downloadLocation =
    context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time
    // Create a job with GenerateOfflineMapParameters and a download directory path
    val generateOfflineMapJob = offlineMapTask.createGenerateOfflineMapJob(
    parameters = parameters,
    downloadDirectoryPath = downloadLocation
    )
    coroutineScope.launch {
    generateOfflineMapJob.progress.collect { progress ->
    updateProgress(progress)
    }
    }
    // Start the job to download the offline map
    generateOfflineMapJob.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()
    }
  5. (Optional) The code in this tutorial calls a function to display messages to the user. One possible implementation of showMessage() is the following.

    MainScreen.kt
    224 collapsed lines
    @file:OptIn(ExperimentalMaterial3Api::class)
    package com.example.app.screens
    import android.content.Context
    import android.widget.Toast
    import androidx.compose.foundation.layout.Column
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.foundation.layout.fillMaxWidth
    import androidx.compose.foundation.layout.padding
    import androidx.compose.material3.ExperimentalMaterial3Api
    import androidx.compose.material3.LinearProgressIndicator
    import androidx.compose.material3.Scaffold
    import androidx.compose.material3.Text
    import androidx.compose.material3.TopAppBar
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.mutableIntStateOf
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.remember
    import androidx.compose.runtime.rememberCoroutineScope
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.platform.LocalContext
    import androidx.compose.ui.res.stringResource
    import com.arcgismaps.Color
    import com.arcgismaps.geometry.Envelope
    import com.arcgismaps.geometry.SpatialReference
    import com.arcgismaps.mapping.ArcGISMap
    import com.arcgismaps.mapping.PortalItem
    import com.arcgismaps.mapping.symbology.SimpleFillSymbol
    import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
    import com.arcgismaps.mapping.symbology.SimpleLineSymbol
    import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
    import com.arcgismaps.mapping.view.Graphic
    import com.arcgismaps.mapping.view.GraphicsOverlay
    import com.arcgismaps.portal.Portal
    import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
    import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
    import com.arcgismaps.toolkit.geoviewcompose.MapView
    import com.example.app.R
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.launch
    import java.util.Calendar
    @Composable
    fun MainScreen() {
    val context = LocalContext.current
    val 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 map
    val offlineMapTask = OfflineMapTask(map)
    // Create a default set of parameters for generating the offline map from the area of interest
    offlineMapTask.createDefaultGenerateOfflineMapParameters(offlineArea)
    .onSuccess { parameters ->
    // When the parameters are successfully created, show progress bar and message
    showProgressBar.value = true
    showMessage(context, "Default parameters have been created.")
    // Download the offline map
    downloadOfflineMapArea(
    context = context,
    coroutineScope = coroutineScope,
    offlineMapTask = offlineMapTask,
    parameters = parameters,
    updateProgress = { currentProgress.intValue = it },
    onDownloadOfflineMapSuccess = { offlineMap ->
    // Hide progress bar and show message when the job executes successfully
    showProgressBar.value = false
    showMessage(context, "Downloaded offline map area successfully.")
    // Replace the current map with the result offline map
    map = offlineMap
    // Clear the offline area outline
    graphicsOverlay.graphics.clear()
    },
    onDownloadOfflineMapFailure = {
    showProgressBar.value = false
    showMessage(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 offline
    val 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 offline
    val 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 overlay
    onOfflineAreaCreated(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 map
    val downloadLocation =
    context.getExternalFilesDir(null)?.path + "OfflineMap_" + Calendar.getInstance().time
    // Create a job with GenerateOfflineMapParameters and a download directory path
    val generateOfflineMapJob = offlineMapTask.createGenerateOfflineMapJob(
    parameters = parameters,
    downloadDirectoryPath = downloadLocation
    )
    coroutineScope.launch {
    generateOfflineMapJob.progress.collect { progress ->
    updateProgress(progress)
    }
    }
    // Start the job to download the offline map
    generateOfflineMapJob.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()
    }
  6. 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. Learn more 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

  1. Click the Download solution link in the right-hand side of this page.

  2. Unzip the file to a location on your machine.

  3. Run Android Studio.

  4. 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 ArcGIS Location Services, also referred to as Location Services, are services hosted by Esri that provide geospatial functionality for developing mapping applications. They include the ArcGIS Basemap Styles service, ArcGIS Static Basemap Tiles service, ArcGIS Places service, ArcGIS Geocoding service, ArcGIS Routing service, ArcGIS GeoEnrichment service, and ArcGIS Elevation service. An ArcGIS Location Platform or ArcGIS Online account is required to use the services. Learn more used in this tutorial, you must implement API key authentication API key authentication is a type of authentication that uses an API key to authenticate requests to ArcGIS services and secure portal items. Learn more or user authentication User authentication is a type of authentication that allows users with an ArcGIS account to sign into an application and allow it to access ArcGIS content, services, and resources on their behalf. The typical authorization protocol used is OAuth2.0. Learn more using an ArcGIS Location Platform An ArcGIS Location Platform account, formerly known as an ArcGIS Developer account, is an identity associated with an ArcGIS Location Platform subscription. Learn more or an ArcGIS Online An ArcGIS Online account, also known as an ArcGIS Organization account, is an identity associated with an ArcGIS Online subscription. It can be used to access ArcGIS tools and develop applications with ArcGIS location services for an organization. Learn more account.

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 An access token is an authorization string that provides access to secure ArcGIS content, data, and services. Its capabilities are determined by the privileges it supports. It is obtained by implementing API key authentication, User authentication, or App authentication. Learn more with privileges Privileges are a set of permissions assigned to ArcGIS accounts, developer credentials, and applications that grant access to secure resources and functionality in ArcGIS. Learn more to access the secure resources used in this tutorial.

  1. 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. Learn more :

    • Privileges
      • Location services > Basemaps
  2. Copy and paste the API key access token into a safe location. It will be used in a later step.

Set developer credentials in the solution

To allow your app users to access ArcGIS location services ArcGIS Location Services, also referred to as Location Services, are services hosted by Esri that provide geospatial functionality for developing mapping applications. They include the ArcGIS Basemap Styles service, ArcGIS Static Basemap Tiles service, ArcGIS Places service, ArcGIS Geocoding service, ArcGIS Routing service, ArcGIS GeoEnrichment service, and ArcGIS Elevation service. An ArcGIS Location Platform or ArcGIS Online account is required to use the services. Learn more , use the developer credentials that you created in the Set up authentication step to authenticate requests for resources.

  1. In the Android view of Android Studio, open app > kotlin+java > com.example.app > MainActivity. Set the AuthenticationMode to .API_KEY.

    MainActivity.kt
    14 collapsed lines
    package com.example.app
    import android.os.Bundle
    import androidx.activity.ComponentActivity
    import androidx.activity.compose.setContent
    import androidx.activity.enableEdgeToEdge
    import com.arcgismaps.ApiKey
    import com.arcgismaps.ArcGISEnvironment
    import com.arcgismaps.httpcore.authentication.OAuthUserConfiguration
    import com.arcgismaps.toolkit.authentication.AuthenticatorState
    import com.arcgismaps.toolkit.authentication.DialogAuthenticator
    import com.example.app.screens.MainScreen
    import com.example.app.ui.theme.TutorialTheme
    class MainActivity : ComponentActivity() {
    private enum class AuthenticationMode { API_KEY, USER_AUTH }
    private val authenticationMode = AuthenticationMode.API_KEY
    42 collapsed lines
    private 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)
    }
    }
    }
    }
    }
  2. Set the apiKey property with your API key access token.

    MainActivity.kt
    22 collapsed lines
    package com.example.app
    import android.os.Bundle
    import androidx.activity.ComponentActivity
    import androidx.activity.compose.setContent
    import androidx.activity.enableEdgeToEdge
    import com.arcgismaps.ApiKey
    import com.arcgismaps.ArcGISEnvironment
    import com.arcgismaps.httpcore.authentication.OAuthUserConfiguration
    import com.arcgismaps.toolkit.authentication.AuthenticatorState
    import com.arcgismaps.toolkit.authentication.DialogAuthenticator
    import com.example.app.screens.MainScreen
    import com.example.app.ui.theme.TutorialTheme
    class MainActivity : ComponentActivity() {
    private enum class AuthenticationMode { API_KEY, USER_AUTH }
    private val authenticationMode = AuthenticationMode.API_KEY
    private 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 lines
    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)
    }
    }
    }
    }
    }

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.

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 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. Learn more 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.

What’s next?

Learn how to use additional API features, ArcGIS location services, and ArcGIS tools in these tutorials: