Skip to content
View on GitHubSample viewer app

Take a web map offline.

Image of generate offline map

Use case

Taking a web map offline allows users continued productivity when their network connectivity is poor or nonexistent. For example, by taking a map offline, a field worker inspecting utility lines in remote areas could still access a feature's location and attribute information.

How to use the sample

Once the map loads, zoom to the extent you want to take offline. The red border shows the extent that will be downloaded. Tap the "Take Map Offline" button to start the offline map job. The progress bar will show the job's progress. When complete, the offline map will replace the online map in the map view.

How it works

  1. Create an ArcGISMap with a PortalItem pointing to the web map.
  2. Create GenerateOfflineMapParameters specifying the download area geometry, minimum scale, and maximum scale.
  3. Create an OfflineMapTask with the map.
  4. Create the OfflineMapJob with OfflineMapTask.generateOfflineMap(params, downloadDirectoryPath) and start it with OfflineMapJob.start().
  5. When the job is done, get the offline map with OfflineMapJob.result.offlineMap.

Relevant API

  • GenerateOfflineMapJob
  • GenerateOfflineMapParameters
  • GenerateOfflineMapResult
  • OfflineMapTask
  • Portal

About the data

The map used in this sample shows the stormwater network within Naperville, IL, USA, with cartography designed for web and mobile devices with offline support.

Additional information

The creation of the offline map can be fine-tuned using parameter overrides for feature layers, or by using local basemaps to achieve more customised results. Also, this sample uses the GeoView-Compose Toolkit module to be able to implement a composable MapView.

Tags

download, geoview-compose, offline, save, web map

Sample Code

MapViewModel.ktMapViewModel.ktMainActivity.ktMainScreen.kt
Use dark colors for code blocksCopy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 /* Copyright 2024 Esri  *  * Licensed under the Apache License, Version 2.0 (the "License");  * you may not use this file except in compliance with the License.  * You may obtain a copy of the License at  *  * http://www.apache.org/licenses/LICENSE-2.0  *  * Unless required by applicable law or agreed to in writing, software  * distributed under the License is distributed on an "AS IS" BASIS,  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  * See the License for the specific language governing permissions and  * limitations under the License.  *  */  package com.esri.arcgismaps.sample.generateofflinemap.components  import android.app.Application import androidx.compose.material3.SnackbarHostState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.unit.IntSize import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.arcgismaps.geometry.Envelope import com.arcgismaps.mapping.ArcGISMap import com.arcgismaps.mapping.PortalItem 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.mapping.view.ScreenCoordinate import com.arcgismaps.portal.Portal import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapJob import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask import com.arcgismaps.toolkit.geoviewcompose.MapViewProxy import com.esri.arcgismaps.sample.generateofflinemap.R import com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.io.File  class MapViewModel(private val application: Application) : AndroidViewModel(application) {   // Create a symbol to show a box around the extent we want to download  private val downloadArea: Graphic = Graphic(  symbol = SimpleLineSymbol(  style = SimpleLineSymbolStyle.Solid,  color = com.arcgismaps.Color.red,  width = 2F  )  )   // Create graphic overlay to add graphics  val graphicsOverlay = GraphicsOverlay()   // Create a ViewModel to handle dialog interactions.  val messageDialogVM: MessageDialogViewModel = MessageDialogViewModel()   // Define button to take a map offline  var takeMapOfflineButtonText by mutableStateOf(application.getString(R.string.take_map_offline))  private set   // Defined to send messages related to offlineMapJob  val snackbarHostState = SnackbarHostState()   // Define map that returns an ArcGISMap  var map by mutableStateOf(ArcGISMap())  private set   // Determinate job progress loading dialog visibility state  var showJobProgressDialog by mutableStateOf(false)  private set   // Determinate job progress percentage  var offlineMapJobProgress by mutableIntStateOf(0)  private set   // Job used to run the offlineMap task on a service  private var offlineMapJob: GenerateOfflineMapJob? = null   // Create a MapViewProxy to handle MapView operations  val mapViewProxy = MapViewProxy()   // Create an IntSize to retrieve dimensions of the map  private var mapViewSize by mutableStateOf(IntSize(0, 0))   init {  // Set up the portal item to take offline  setUpMap()  }   /**  * Sets up a portal item and displays map area to take offline  */  private fun setUpMap() {   // Create a portal item with the itemId of the web map  val portal = Portal(application.getString(R.string.portal_url))  val portalItem = PortalItem(portal, application.getString(R.string.item_id))   // Clear, then add the download graphic to the graphics overlay  graphicsOverlay.graphics.clear()  graphicsOverlay.graphics.add(downloadArea)   map = ArcGISMap(portalItem)  viewModelScope.launch(Dispatchers.Main) {  map.load()  .onFailure {  messageDialogVM.showMessageDialog(  title = it.message.toString()  )  }  .onSuccess {  // Limit the map scale to the largest layer scale  map.maxScale = map.operationalLayers[6].maxScale ?: 0.0  map.minScale = map.operationalLayers[6].minScale ?: 0.0  }  }  }   /**  * Generate an offline map job with the default [GenerateOfflineMapParameters]  *  */  fun createOfflineMapJob() {  // Offline map path  val offlineMapPath =  application.getExternalFilesDir(null)?.path + File.separator + "offlineMap"   // Delete any offline map already in the cache  File(offlineMapPath).deleteRecursively()   // Specify the extent, min scale, and max scale as parameters  var minScale: Double = map.minScale ?: 0.0  val maxScale: Double = map.maxScale ?: 0.0   // Variable minScale must always be larger than maxScale  if (minScale <= maxScale) {  minScale = maxScale + 1  }   // Get the geometry of the download area  val geometry = downloadArea.geometry ?: return messageDialogVM.showMessageDialog(  title = "Could not get geometry of the downloadArea"  )   // Set the offline map parameters  val generateOfflineMapParameters = GenerateOfflineMapParameters(  areaOfInterest = geometry,  minScale = minScale,  maxScale = maxScale  ).apply {  // Set job to cancel on any errors  continueOnErrors = false  }   // Create an offline map task with the map  val offlineMapTask = OfflineMapTask(onlineMap = map)   viewModelScope.launch(Dispatchers.Main) {  offlineMapTask.load().getOrElse {  messageDialogVM.showMessageDialog(  title = it.message.toString(),  description = it.cause.toString()  )  }  }   // Create an offline map job with the download directory path and parameters and start the job  offlineMapJob = offlineMapTask.createGenerateOfflineMapJob(  parameters = generateOfflineMapParameters,  downloadDirectoryPath = offlineMapPath  )   runOfflineMapJob()   }   /**  * Starts the [GenerateOfflineMapJob], shows the progress dialog and  * displays the result offline map to the MapView  */  private fun runOfflineMapJob() {   offlineMapJob?.let { offlineMapJob ->   // Show the Job Progress Dialog  showJobProgressDialog = true   with(viewModelScope) {   // Create a flow-collection for the job's progress  launch(Dispatchers.Main) {  offlineMapJob.progress.collect { progress ->  // Display the current job's progress value  offlineMapJobProgress = progress  }  }   launch(Dispatchers.IO) {  // Start the job and wait for Job result  offlineMapJob.start()  offlineMapJob.result().onSuccess {  // Set the offline map result as the displayed map and clear the red bounding box graphic  map = it.offlineMap  graphicsOverlay.graphics.clear()   // Change the button text to Reset Map once job is done successfully  takeMapOfflineButtonText = application.getString(R.string.reset_map)   // Dismiss the progress dialog  showJobProgressDialog = false   // Show user where map was locally saved  snackbarHostState.showSnackbar(message = "Map saved at: " + offlineMapJob.downloadDirectoryPath)   }.onFailure { throwable ->  messageDialogVM.showMessageDialog(  title = throwable.message.toString(),  description = throwable.cause.toString()  )  showJobProgressDialog = false  }  }  }   }  }   fun cancelOfflineMapJob() {  with(viewModelScope) {  launch(Dispatchers.IO) {  offlineMapJob?.cancel()  }  launch(Dispatchers.Main) {  snackbarHostState.showSnackbar(message = "User canceled.")  }  }  }   fun updateMapViewSize(size: IntSize) {  mapViewSize = size  }   /**  * Clear the preview map and set up mapView again  */  fun resetButtonClick() {   // Add the download graphic to the graphics overlay  graphicsOverlay.graphics.clear()   // Change button text to Take Map Offline on reset  takeMapOfflineButtonText = application.getString(R.string.take_map_offline)   // Set up the portal item to take offline  setUpMap()   }   /**  * Use map view's size to determine dimensions of the map to get the download offline area  * and use [MapViewProxy] to assist in converting screen points to map points  */  fun calculateDownloadOfflineArea() {   // Upper left corner of the area to take offline  val minScreenPoint = ScreenCoordinate(200.0, 200.0)   // Lower right corner of the downloaded area  val maxScreenPoint = ScreenCoordinate(  x = mapViewSize.width - 200.0,  y = mapViewSize.height - 200.0  )   // Convert screen points to map points  val minPoint = mapViewProxy.screenToLocationOrNull(minScreenPoint)  val maxPoint = mapViewProxy.screenToLocationOrNull(maxScreenPoint)   // Create an envelope to set the download area's geometry using the defined bounds  if (minPoint != null && maxPoint != null) {  val envelope = Envelope(minPoint, maxPoint)  downloadArea.geometry = envelope  }  } }

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.