Create and save a map as a web map item to an ArcGIS portal.

Use case
Maps can be created programmatically in code and then serialized and saved as an ArcGIS portal item. In this case, the portal item is a web map which can be shared with others and opened in various applications and APIs throughout the platform, such as ArcGIS Pro, ArcGIS Online, the JavaScript API, Collector, and Explorer.
How to use the sample
When you run the sample, you will be challenged for an ArcGIS Online login. Enter a username and password for an ArcGIS Online named user account (such as your ArcGIS for Developers account). Then, tap the Edit Map button to choose the basemap and layers for your new map. To save the map, add a title, tags and description (optional), and a folder on your portal (you will need to create one in your portal’s My Content section if you don’t already have one). Click the Save to Account button to save the map to the chosen folder.
How it works
- Configure an
AuthenticatorStateto handle authentication challenges. - Add the
AuthenticatorStateto aDialogAuthenticatorin the app’sMainActivityto invoke the authentication challenge. - Create a new
Portaland load it. - Access the
PortalUserContentwithportal.portalInfo?.user?.fetchContent()?.onSuccess, to get the user’s list of portal folders withportalUserContent.folders. - Create an
ArcGISMapwith aBasemapStyleand a few operational layers. - Call
ArcGISMap.saveMap()to save a newArcGISMapwith the specified title, tags, and folder to the portal.
Relevant API
- ArcGISMap
- Portal
Additional information
This sample uses the toolkit’s authentication module to handle authentication. For information about setting up the toolkit, as well as code for the underlying component, visit the toolkit docs. This sample also uses the GeoView-Compose Toolkit module to be able to implement a composable MapView.
Tags
ArcGIS Online, ArcGIS Pro, geoview-compose, portal, publish, share, web map
Sample Code
/* 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.createandsavemap
import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Surfaceimport androidx.compose.runtime.Composableimport androidx.lifecycle.viewmodel.compose.viewModelimport com.arcgismaps.toolkit.authentication.DialogAuthenticatorimport com.esri.arcgismaps.sample.createandsavemap.components.MapViewModelimport com.esri.arcgismaps.sample.createandsavemap.screens.MainScreenimport com.esri.arcgismaps.sample.sampleslib.theme.SampleAppTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { SampleAppTheme { SampleApp() } } }
@Composable private fun SampleApp() { val mapViewModel: MapViewModel = viewModel() Surface( color = MaterialTheme.colorScheme.background ) { MainScreen( sampleName = getString(R.string.create_and_save_map_app_name) ) }
// authenticator at bottom can draw over the top of the sample DialogAuthenticator(authenticatorState = mapViewModel.authenticatorState) }}/* 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.createandsavemap.components
import android.app.Applicationimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValueimport androidx.lifecycle.AndroidViewModelimport androidx.lifecycle.viewModelScopeimport com.arcgismaps.httpcore.authentication.OAuthUserConfigurationimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.Basemapimport com.arcgismaps.mapping.BasemapStyleimport com.arcgismaps.mapping.Viewpointimport com.arcgismaps.mapping.layers.ArcGISMapImageLayerimport com.arcgismaps.mapping.layers.Layerimport com.arcgismaps.portal.Portalimport com.arcgismaps.portal.PortalFolderimport com.arcgismaps.toolkit.authentication.AuthenticatorStateimport com.esri.arcgismaps.sample.createandsavemap.Rimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModelimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.launch
class MapViewModel(application: Application) : AndroidViewModel(application) {
// view model to handle popup dialogs val messageDialogVM = MessageDialogViewModel()
// set up authenticator state to handle authentication challenges val authenticatorState = AuthenticatorState().apply { oAuthUserConfigurations = listOf( OAuthUserConfiguration( portalUrl = application.getString(R.string.portal_url), clientId = application.getString(R.string.client_id), redirectUrl = application.getString(R.string.redirect_url) ) ) }
// require use of user credential to load portal private val portal = Portal("https://www.arcgis.com", Portal.Connection.Authenticated)
// update displayed map once user is authenticated var arcGISMap by mutableStateOf(ArcGISMap())
// folders on portal associated with the authenticated user private val _portalFolders = MutableStateFlow<List<PortalFolder>>(listOf()) val portalFolders = _portalFolders.asStateFlow()
// define a couple of feature layers to be loaded private val worldElevation = ArcGISMapImageLayer("https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer") private val usCensus = ArcGISMapImageLayer("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer") val availableLayers: List<Layer> = listOf(worldElevation, usCensus)
// associate basemap styles with friendly names val stylesMap: Map<String, BasemapStyle> = mapOf( Pair("Streets", BasemapStyle.ArcGISStreets), Pair("Imagery", BasemapStyle.ArcGISImageryStandard), Pair("Topographic", BasemapStyle.ArcGISTopographic), Pair("Oceans", BasemapStyle.ArcGISOceans) )
// properties hoisted from UI bottom sheet
var selectedBasemapStyle by mutableStateOf("Streets") private set
fun updateBasemapStyle(style: String) { selectedBasemapStyle = style
// update map to display selected basemap style arcGISMap.setBasemap(Basemap(stylesMap.getValue(selectedBasemapStyle))) }
fun updateActiveLayers(layer: Layer) { arcGISMap.operationalLayers.apply { if (contains(layer)) { remove(layer) } else { add(layer) } } }
var mapName by mutableStateOf("My Map") private set
fun updateName(name: String) { mapName = name }
var mapTags by mutableStateOf("map, census, layers") private set
fun updateTags(tags: String) { mapTags = tags }
var portalFolder by mutableStateOf<PortalFolder?>(null)
fun updateFolder(folder: PortalFolder?) { portalFolder = folder }
var mapDescription by mutableStateOf("") private set
fun updateDescription(description: String) { mapDescription = description }
init { viewModelScope.launch { portal.load().onSuccess { // when the user has successfully authenticated and the portal is loaded...
// populate the portal folders flow portal.portalInfo?.apply { this.user?.fetchContent()?.onSuccess { _portalFolders.value = it.folders } }
// load the streets basemap and set an initial viewpoint arcGISMap = ArcGISMap(BasemapStyle.ArcGISStreets).apply { initialViewpoint = Viewpoint(38.85, -90.2, 1e7) }
// load operational layers worldElevation.load() usCensus.load() }.onFailure { // login was cancelled or failed to authenticate messageDialogVM.showMessageDialog( application.getString(R.string.createAndSaveMap_failedToLoadPortal), it.message.toString() ) } } }
/** * Saves the map to a user's account. */ suspend fun save(): Result<Unit> { return arcGISMap.saveAs( portal, description = mapDescription, folder = portalFolder, tags = mapTags.split(",").map { str -> str.trim() }, forceSaveToSupportedVersion = false, thumbnail = null, title = mapName ) }
}/* 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.createandsavemap.screens
import androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.navigationBarsPaddingimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.wrapContentHeightimport androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.foundation.verticalScrollimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.Editimport androidx.compose.material3.BottomSheetScaffoldimport androidx.compose.material3.Buttonimport androidx.compose.material3.Checkboximport androidx.compose.material3.DropdownMenuItemimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.ExposedDropdownMenuBoximport androidx.compose.material3.ExposedDropdownMenuDefaultsimport androidx.compose.material3.FloatingActionButtonimport androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.Iconimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.MenuAnchorTypeimport androidx.compose.material3.OutlinedTextFieldimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.SnackbarHostimport androidx.compose.material3.SnackbarHostStateimport androidx.compose.material3.Textimport androidx.compose.material3.rememberBottomSheetScaffoldStateimport androidx.compose.material3.rememberStandardBottomSheetStateimport androidx.compose.runtime.Composableimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalConfigurationimport androidx.compose.ui.text.input.ImeActionimport androidx.compose.ui.unit.dpimport androidx.lifecycle.viewmodel.compose.viewModelimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.BasemapStyleimport com.arcgismaps.mapping.layers.Layerimport com.arcgismaps.portal.PortalFolderimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.esri.arcgismaps.sample.createandsavemap.components.MapViewModelimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogimport com.esri.arcgismaps.sample.sampleslib.components.SampleTopAppBarimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.launch
/** * Main screen layout for the sample app */@OptIn(ExperimentalMaterial3Api::class)@Composablefun MainScreen(sampleName: String) { // create a ViewModel to handle MapView interactions val mapViewModel: MapViewModel = viewModel()
val composableScope = rememberCoroutineScope() val snackbarHostState = remember { SnackbarHostState() } val controlsBottomSheetState = rememberBottomSheetScaffoldState( bottomSheetState = rememberStandardBottomSheetState(skipHiddenState = false).apply { composableScope.launch { hide() } } )
Scaffold( snackbarHost = { SnackbarHost(hostState = snackbarHostState) }, topBar = { SampleTopAppBar(title = sampleName) }, content = { Box( modifier = Modifier .fillMaxSize() .padding(it), contentAlignment = Alignment.Center ) { // map view not shown until the portal is loaded and a basemap has been set MapView( arcGISMap = mapViewModel.arcGISMap, Modifier.fillMaxSize(), )
// show the "Edit map" button only when the bottom sheet is not visible if (!controlsBottomSheetState.bottomSheetState.isVisible) { FloatingActionButton( modifier = Modifier .align(Alignment.BottomEnd) .padding(bottom = 36.dp, end = 24.dp), onClick = { composableScope.launch { controlsBottomSheetState.bottomSheetState.show() } }) { Icon(Icons.Filled.Edit, contentDescription = "Edit map button") Spacer(Modifier.padding(8.dp)) } }
BottomSheetScaffold( modifier = Modifier.wrapContentHeight(), scaffoldState = controlsBottomSheetState, sheetPeekHeight = LocalConfiguration.current.screenHeightDp.dp.times(0.33f), sheetContent = { Column( Modifier .padding(12.dp) .navigationBarsPadding() .verticalScroll(rememberScrollState()) ) { CreateMapBottomSheet( mapViewModel = mapViewModel )
Button( modifier = Modifier .align(Alignment.CenterHorizontally) .padding(12.dp), onClick = { composableScope.launch { // dismiss bottom sheet immediately controlsBottomSheetState.bottomSheetState.hide()
// report success in a snack bar, failure in a popup mapViewModel.save().onSuccess { snackbarHostState.showSnackbar( "Map saved to portal.", withDismissAction = true ) }.onFailure { err -> mapViewModel.messageDialogVM.showMessageDialog( "Error", err.message.toString() ) } } }) { Text("Save to account") } } Spacer(Modifier.size(8.dp)) } ) {} }
// message dialog can draw over all other content in the main screen mapViewModel.messageDialogVM.apply { if (dialogStatus) { MessageDialog( title = messageTitle, description = messageDescription, onDismissRequest = ::dismissDialog ) } } } )}
/** * Composable function to populate bottom sheet with sample options. */@Composablefun CreateMapBottomSheet( mapViewModel: MapViewModel) {
Column( modifier = Modifier.padding(vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { Text( text = "Choose map settings:", style = MaterialTheme.typography.titleMedium ) BasemapDropdown( mapViewModel.selectedBasemapStyle, mapViewModel.stylesMap, mapViewModel::updateBasemapStyle )
LayersDropdown( mapViewModel.availableLayers, mapViewModel.arcGISMap, mapViewModel::updateActiveLayers )
HorizontalDivider(Modifier.padding(vertical = 12.dp, horizontal = 8.dp))
OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = mapViewModel.mapName, onValueChange = { newName -> mapViewModel.updateName(newName) }, label = { Text(text = "Enter map name:") }, singleLine = true, )
OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = mapViewModel.mapTags, onValueChange = { newTags -> mapViewModel.updateTags(newTags) }, label = { Text(text = "Tags:") }, singleLine = true, )
FolderDropdown( mapViewModel.portalFolder, mapViewModel.portalFolders, mapViewModel::updateFolder )
OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = mapViewModel.mapDescription, onValueChange = { newDescription -> mapViewModel.updateDescription(newDescription) }, label = { Text(text = "Description:") }, keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done) ) }}
/** * Composable function to display portal folder dropdown in the bottom sheet. */@OptIn(ExperimentalMaterial3Api::class)@Composablefun FolderDropdown( currentFolder: PortalFolder?, portalFolders: StateFlow<List<PortalFolder>>, updateFolder: (PortalFolder?) -> Unit) {
var expanded by rememberSaveable { mutableStateOf(false) }
ExposedDropdownMenuBox( modifier = Modifier.fillMaxWidth(), expanded = expanded, onExpandedChange = { expanded = !expanded } ) { var label by remember { mutableStateOf( currentFolder?.title ?: "(No folder)" ) }
OutlinedTextField( modifier = Modifier .fillMaxWidth() .menuAnchor(type = MenuAnchorType.PrimaryNotEditable), value = label, onValueChange = { newDescription -> label = newDescription }, label = { Text(text = "Folder:") }, readOnly = true, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) } )
ExposedDropdownMenu( expanded = expanded, onDismissRequest = { expanded = false }, Modifier.padding(vertical = 0.dp) ) { val folders by portalFolders.collectAsState(initial = listOf()) if (folders.isEmpty()) { Text("No folders to display", Modifier.padding(8.dp)) } else { DropdownMenuItem( text = { Text("(No folder)") }, onClick = { updateFolder(null) label = "(No folder)" expanded = false } ) HorizontalDivider() folders.forEachIndexed { index, folder -> DropdownMenuItem( text = { Text(folder.title) }, onClick = { updateFolder(folder) label = folder.title expanded = false }) // show a divider between dropdown menu options if (index < folders.lastIndex) { HorizontalDivider() } } } } }
}
/** * Composable function to display basemap dropdown in the bottom sheet. */@OptIn(ExperimentalMaterial3Api::class)@Composablefun BasemapDropdown( basemapStyle: String, stylesNameMap: Map<String, BasemapStyle>, updateBasemapStyle: (String) -> Unit) { var expanded by rememberSaveable { mutableStateOf(false) }
ExposedDropdownMenuBox( modifier = Modifier.fillMaxWidth(), expanded = expanded, onExpandedChange = { expanded = !expanded } ) { OutlinedTextField( modifier = Modifier .fillMaxWidth() .menuAnchor(type = MenuAnchorType.PrimaryNotEditable), value = basemapStyle, onValueChange = {}, label = { Text(text = "Basemap Style:") }, readOnly = true, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) } )
ExposedDropdownMenu( expanded = expanded, onDismissRequest = { expanded = false }, Modifier.padding(vertical = 0.dp) ) {
stylesNameMap.keys.toList().forEachIndexed { index, basemapName -> DropdownMenuItem( text = { Text(basemapName) }, onClick = { updateBasemapStyle(basemapName) expanded = false }) // show a divider between dropdown menu options if (index < stylesNameMap.keys.toList().lastIndex) { HorizontalDivider() } } } }}
/** * Composable function to display active layers dropdown in the bottom sheet. */@OptIn(ExperimentalMaterial3Api::class)@Composablefun LayersDropdown( availableLayers: List<Layer>, arcGISMap: ArcGISMap, updateActiveLayers: (Layer) -> Unit
) { var expanded by rememberSaveable { mutableStateOf(false) }
ExposedDropdownMenuBox( modifier = Modifier.fillMaxWidth(), expanded = expanded, onExpandedChange = { expanded = !expanded } ) { OutlinedTextField( modifier = Modifier .fillMaxWidth() .menuAnchor(type = MenuAnchorType.PrimaryNotEditable), value = "Select...", onValueChange = {}, label = { Text(text = "Operational Layers:") }, readOnly = true, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) } )
ExposedDropdownMenu( expanded = expanded, onDismissRequest = { expanded = false } ) { availableLayers.forEachIndexed { index, layer -> var checked by mutableStateOf( arcGISMap.operationalLayers.contains(layer) ) Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(8.dp) ) { Text(layer.name, Modifier.weight(1f)) Checkbox( checked = checked, onCheckedChange = { updateActiveLayers(layer) checked = !checked } ) } // show a divider between dropdown menu options if (index < availableLayers.lastIndex) { HorizontalDivider() } } } }}