Demonstrates how to get the network state and validate the topology of a utility network.

Use case
Dirty areas are generated where edits to utility network features have not been evaluated against the network rules. Tracing across this area could result in an error or return inaccurate results. Validating the utility network updates the network topology with the edited feature data, maintaining consistency between the features and topology. Querying the network state allows you to determine if there are dirty areas or errors in a utility network, and if it supports network topology.
How to use the sample
Select features to make edits and then use ‘Apply’ to send edits to the server.
- Click ‘Get state’ to check if validate is required or if tracing is available.
- Click ‘Validate’ to validate network topology and clear dirty areas.
- Click ‘Trace’ to run a trace.
How it works
- Create and load an
ArcGISMapwith a web map item URL. - Load the
UtilityNetworkfrom the web map and switch itsServiceGeodatabaseto a new branch version. - Add
LabelDefinitions for the fields that will be updated on a feature edit. - Add the
UtilityNetwork.dirtyAreaTableto the map to visualize dirty areas or errors. - Set a default starting location and trace parameters to stop traversability on an open device.
- Get the
UtilityNetworkCapabilitiesfrom theUtilityNetworkDefinitionand use these values to enable or disable the ‘Get state’, ‘Validate’, and ‘Trace’ buttons. - When an
ArcGISFeatureis selected for editing, populate the choice list for the field value using the field’sCodedValueDomain.codedValues. - When ‘Apply’ is clicked, update the value of the selected feature’s attribute value with the selected
CodedValue.codeand callServiceGeodatabase.applyEdits(). - When ‘Get state’ is clicked, call
UtilityNetwork.getState()and print the results. - When ‘Validate’ is clicked, get the current map extent and call
UtilityNetwork.validateNetworkTopology(...). - When ‘Trace’ is clicked, call
UtilityNetwork.trace(...)with the predefined parameters and select all features returned. - When ‘Clear Selection’ or ‘Cancel’ are clicked, clear all selected features on each layer in the map and close the attribute picker.
Relevant API
- UtilityElement
- UtilityElementTraceResult
- UtilityNetwork
- UtilityNetworkCapabilities
- UtilityNetworkState
- UtilityNetworkValidationJob
- UtilityTraceConfiguration
- UtilityTraceParameters
- UtilityTraceResult
About the data
The Naperville electric feature service contains a utility network that can be used to query the network state and validate network topology before tracing. The Naperville electric webmap uses the same feature service endpoint and is shown in this sample. Authentication is required and handled within the sample code.
Additional information
Starting from 200.4, an Advanced Editing extension license is required for editing a utility network in the following cases:
- Stand-alone mobile geodatabase that is exported from ArcGIS Pro 2.7 or higher
- Sync-enabled mobile geodatabase that is generated from an ArcGIS Enterprise Feature Service 11.2 or higher
- Webmap or service geodatabase that points to an ArcGIS Enterprise Feature Service 11.2 or higher
Please refer to the “Advanced Editing” section in the extension license table in License levels and capabilities for details.
Tags
dirty areas, edit, network topology, online, state, trace, utility network, validate
Sample Code
/* Copyright 2025 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.validateutilitynetworktopology
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 com.arcgismaps.ApiKeyimport com.arcgismaps.ArcGISEnvironmentimport com.esri.arcgismaps.sample.sampleslib.theme.SampleAppThemeimport com.esri.arcgismaps.sample.validateutilitynetworktopology.screens.ValidateUtilityNetworkTopologyScreen
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // authentication with an API key or named user is // required to access basemaps and other location services ArcGISEnvironment.apiKey = ApiKey.create(BuildConfig.ACCESS_TOKEN)
enableEdgeToEdge() setContent { SampleAppTheme { ValidateUtilityNetworkTopologyApp() } } }
@Composable private fun ValidateUtilityNetworkTopologyApp() { Surface(color = MaterialTheme.colorScheme.background) { ValidateUtilityNetworkTopologyScreen( sampleName = getString(R.string.validate_utility_network_topology_app_name) ) } }}/* Copyright 2025 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. * */@file:OptIn(ExperimentalMaterial3Api::class)
package com.esri.arcgismaps.sample.validateutilitynetworktopology.screens
import android.content.res.Configurationimport androidx.compose.animation.animateContentSizeimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.wrapContentSizeimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.grid.GridCellsimport androidx.compose.foundation.lazy.grid.LazyVerticalGridimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.Checkimport androidx.compose.material.icons.filled.KeyboardArrowDownimport androidx.compose.material.icons.filled.KeyboardArrowUpimport androidx.compose.material3.Buttonimport androidx.compose.material3.Cardimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.Iconimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.ModalBottomSheetimport androidx.compose.material3.OutlinedButtonimport androidx.compose.material3.OutlinedIconButtonimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Surfaceimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport androidx.lifecycle.compose.collectAsStateWithLifecycleimport androidx.lifecycle.viewmodel.compose.viewModelimport com.arcgismaps.Colorimport com.arcgismaps.data.CodedValueimport com.arcgismaps.mapping.view.SelectionPropertiesimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.esri.arcgismaps.sample.sampleslib.components.LoadingDialogimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogimport com.esri.arcgismaps.sample.sampleslib.components.SampleTopAppBarimport com.esri.arcgismaps.sample.sampleslib.theme.SampleAppThemeimport com.esri.arcgismaps.sample.validateutilitynetworktopology.components.ValidateUtilityNetworkTopologyViewModel
/** * Main screen layout for the sample app */@Composablefun ValidateUtilityNetworkTopologyScreen(sampleName: String) { val mapViewModel: ValidateUtilityNetworkTopologyViewModel = viewModel()
// On first composition, initialize the sample. var isViewmodelInitialized by rememberSaveable { mutableStateOf(false) } LaunchedEffect(Unit) { if (!isViewmodelInitialized) { mapViewModel.initialize() isViewmodelInitialized = true } } // Display loading dialog on initialization if (!isViewmodelInitialized) { LoadingDialog("Loading utility network") }
// Collect UI states from the ViewModel val statusMessage by mapViewModel.statusMessage.collectAsStateWithLifecycle() val canGetState by mapViewModel.canGetState.collectAsStateWithLifecycle() val canValidate by mapViewModel.canValidateNetworkTopology.collectAsStateWithLifecycle() val canTrace by mapViewModel.canTrace.collectAsStateWithLifecycle() val canClearSelection by mapViewModel.canClearSelection.collectAsStateWithLifecycle()
// For editing a feature's coded-value domain var fieldValueOptions by remember { mutableStateOf<List<CodedValue>>(listOf()) } val selectedFieldValue by mapViewModel.selectedFieldValue.collectAsStateWithLifecycle() val selectedFeature by mapViewModel.selectedFeature.collectAsStateWithLifecycle() var selectedFieldAlias by remember { mutableStateOf("") }
// If we are currently editing an attribute, display bottom sheet. var isEditingFeature by remember { mutableStateOf(false) }
// Track when the selected feature changes to display bottom sheet LaunchedEffect(selectedFeature) { isEditingFeature = (selectedFeature != null) fieldValueOptions = mapViewModel.fieldValueOptions.value }
Scaffold( topBar = { SampleTopAppBar(title = sampleName) }, content = { padding -> Box(modifier = Modifier.fillMaxSize().padding(padding)) { MapView( modifier = Modifier .fillMaxSize() .padding(top = 40.dp), arcGISMap = mapViewModel.arcGISMap, mapViewProxy = mapViewModel.mapViewProxy, graphicsOverlays = listOf(mapViewModel.graphicsOverlay), selectionProperties = SelectionProperties(color = Color.cyan), onVisibleAreaChanged = mapViewModel::updateVisibleArea, onSingleTapConfirmed = { tapEvent -> // Identify feature at the tapped location mapViewModel.identifyFeatureAt( screenCoordinate = tapEvent.screenCoordinate, selectedFieldAlias = { selectedFieldAlias = it } ) } ) // Display collapsable status message on top of MapView NetworkStatusMessage(Modifier.align(Alignment.TopCenter), statusMessage) // Display bottom sheet if editing a feature attribute if (isEditingFeature && fieldValueOptions.isNotEmpty()) { ModalBottomSheet( onDismissRequest = { // Clear selection and close sheet mapViewModel.clearFeatureEditSelection() isEditingFeature = false } ) { // Edit feature attribute layout EditFeatureFieldOptions( selectedFieldValueName = selectedFieldValue?.name ?: "(None)", fieldAliasName = selectedFieldAlias, fieldValueOptions = fieldValueOptions, onNewFieldValueSelected = mapViewModel::updateSelectedValue, onCancelButtonSelected = { // Clear selection and close sheet mapViewModel.clearFeatureEditSelection() isEditingFeature = false }, onApplyEditsSelected = { // Apply edits and close sheet mapViewModel.applyEdits() isEditingFeature = false } ) } } } // Handle error or info dialogs from the ViewModel mapViewModel.messageDialogVM.apply { if (dialogStatus) { MessageDialog( title = messageTitle, description = messageDescription, onDismissRequest = ::dismissDialog ) } } }, bottomBar = { // Options to get state, validate, trace or clear features. BottomRowOptions( isGetStateEnabled = canGetState, isValidateEnabled = canValidate, isTraceEnabled = canTrace, isClearSelectionEnabled = canClearSelection, onGetStateSelected = mapViewModel::getState, onValidateSelected = mapViewModel::validateNetworkTopology, onTraceSelected = mapViewModel::trace, onClearSelected = mapViewModel::clearFeatureEditSelection ) } )}
@Composablefun NetworkStatusMessage(modifier: Modifier, statusMessage: String) { var isCollapsed by remember { mutableStateOf(false) } Row( modifier = modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.background.copy(alpha = 0.95f)) .padding(8.dp) .animateContentSize() ) { Text( text = statusMessage, modifier = Modifier .fillMaxWidth() .weight(1f), style = MaterialTheme.typography.labelLarge, maxLines = if (isCollapsed) 1 else 10, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center )
OutlinedIconButton( modifier = Modifier.size(20.dp).padding(1.dp), onClick = { isCollapsed = !isCollapsed } ) { Icon( imageVector = if (isCollapsed) Icons.Default.KeyboardArrowDown else Icons.Default.KeyboardArrowUp, contentDescription = "Expand/Collapse" ) } }
}
@Composablefun EditFeatureFieldOptions( selectedFieldValueName: String, fieldAliasName: String, fieldValueOptions: List<CodedValue>, onNewFieldValueSelected: (CodedValue) -> Unit, onCancelButtonSelected: () -> Unit, onApplyEditsSelected: () -> Unit) { Column( modifier = Modifier .wrapContentSize() .padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { OutlinedButton(onClick = onCancelButtonSelected) { Text("Cancel") } Text( text = "Edit Feature", style = MaterialTheme.typography.titleMedium ) Button(onClick = onApplyEditsSelected) { Text("Apply Edits") } } Text( modifier = Modifier.padding(horizontal = 24.dp), text = fieldAliasName, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSecondaryContainer ) Card(modifier = Modifier.padding(horizontal = 24.dp)) { LazyColumn { fieldValueOptions.forEachIndexed { index, codedValue -> item { Column(modifier = Modifier.clickable { onNewFieldValueSelected(codedValue) }) { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 24.dp, vertical = 8.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = codedValue.name, fontWeight = if (codedValue.name == selectedFieldValueName) FontWeight.Bold else FontWeight.Normal ) if (codedValue.name == selectedFieldValueName) Icon( imageVector = Icons.Default.Check, contentDescription = "Selected field value" ) } if (index <= fieldValueOptions.lastIndex) HorizontalDivider() } } } } } }}
@Composablefun BottomRowOptions( isGetStateEnabled: Boolean, isValidateEnabled: Boolean, isTraceEnabled: Boolean, isClearSelectionEnabled: Boolean, onGetStateSelected: () -> Unit, onValidateSelected: () -> Unit, onTraceSelected: () -> Unit, onClearSelected: () -> Unit) { LazyVerticalGrid( modifier = Modifier .fillMaxWidth() .padding(vertical = 4.dp, horizontal = 24.dp), columns = GridCells.Fixed(2), horizontalArrangement = Arrangement.spacedBy(24.dp) ) { item { Button( onClick = onClearSelected, enabled = isClearSelectionEnabled ) { Text("Clear") } } item { Button( onClick = onGetStateSelected, enabled = isGetStateEnabled ) { Text("Get State") } }
item { Button( onClick = onValidateSelected, enabled = isValidateEnabled ) { Text("Validate") } }
item { Button( onClick = onTraceSelected, enabled = isTraceEnabled ) { Text("Trace") } } }}
@Preview(showBackground = true)@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true)@Composablefun PreviewValidateUtilityNetworkEditDialog() { SampleAppTheme { Surface { EditFeatureFieldOptions( selectedFieldValueName = "14.4 KV", fieldValueOptions = listOf(), onNewFieldValueSelected = { }, onCancelButtonSelected = { }, onApplyEditsSelected = { }, fieldAliasName = "Nominal Voltage" ) } }}
@Preview(showBackground = true)@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true)@Composablefun PreviewValidateUtilityNetworkOptions() { SampleAppTheme { Surface { BottomRowOptions( isGetStateEnabled = true, isValidateEnabled = true, isTraceEnabled = true, isClearSelectionEnabled = true, onGetStateSelected = { }, onValidateSelected = { }, onTraceSelected = { }, onClearSelected = { } ) } }}/* Copyright 2025 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.validateutilitynetworktopology.components
import android.app.Applicationimport androidx.compose.ui.unit.dpimport androidx.lifecycle.AndroidViewModelimport androidx.lifecycle.viewModelScopeimport com.arcgismaps.ArcGISEnvironmentimport com.arcgismaps.Colorimport com.arcgismaps.Guidimport com.arcgismaps.arcgisservices.FeatureServiceSessionTypeimport com.arcgismaps.arcgisservices.ServiceVersionParametersimport com.arcgismaps.arcgisservices.VersionAccessimport com.arcgismaps.data.ArcGISFeatureimport com.arcgismaps.data.CodedValueimport com.arcgismaps.data.CodedValueDomainimport com.arcgismaps.data.Fieldimport com.arcgismaps.data.QueryParametersimport com.arcgismaps.data.ServiceFeatureTableimport com.arcgismaps.data.ServiceGeodatabaseimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.Geometryimport com.arcgismaps.geometry.GeometryEngineimport com.arcgismaps.geometry.Pointimport com.arcgismaps.geometry.Polygonimport com.arcgismaps.httpcore.authentication.ArcGISAuthenticationChallengeHandlerimport com.arcgismaps.httpcore.authentication.ArcGISAuthenticationChallengeResponseimport com.arcgismaps.httpcore.authentication.TokenCredentialimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.Viewpointimport com.arcgismaps.mapping.labeling.LabelDefinitionimport com.arcgismaps.mapping.labeling.SimpleLabelExpressionimport com.arcgismaps.mapping.layers.FeatureLayerimport com.arcgismaps.mapping.layers.SelectionModeimport com.arcgismaps.mapping.symbology.SimpleMarkerSymbolimport com.arcgismaps.mapping.symbology.SimpleMarkerSymbolStyleimport com.arcgismaps.mapping.symbology.TextSymbolimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.mapping.view.ScreenCoordinateimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.geoprocessing.GeoprocessingExecutionTypeimport com.arcgismaps.toolkit.geoviewcompose.MapViewProxyimport com.arcgismaps.utilitynetworks.UtilityElementimport com.arcgismaps.utilitynetworks.UtilityElementTraceResultimport com.arcgismaps.utilitynetworks.UtilityNetworkimport com.arcgismaps.utilitynetworks.UtilityTraceParametersimport com.arcgismaps.utilitynetworks.UtilityTraceTypeimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModelimport com.esri.arcgismaps.sample.validateutilitynetworktopology.components.ValidateUtilityNetworkTopologyViewModel.Companion.PASSWORDimport com.esri.arcgismaps.sample.validateutilitynetworktopology.components.ValidateUtilityNetworkTopologyViewModel.Companion.USERNAMEimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.launchimport kotlinx.coroutines.runBlockingimport java.util.UUID
class ValidateUtilityNetworkTopologyViewModel(application: Application) : AndroidViewModel(application) {
// The map containing the Naperville Electric web map val arcGISMap = ArcGISMap( item = PortalItem( itemId = NAPERVILLE_ELECTRIC_WEBMAP_ITEM_ID, portal = Portal( url = SAMPLE_SERVER_7_PORTAL, connection = Portal.Connection.Authenticated ) ) ).apply { initialViewpoint = Viewpoint(center = Point(-9815160.0, 5128780.0), scale = 4000.0) // Set the map to load in persistent session mode (workaround for server caching issue) // https://support.esri.com/en-us/bug/asynchronous-validate-request-for-utility-network-servi-bug-000160443 loadSettings.featureServiceSessionType = FeatureServiceSessionType.Persistent }
// Used to update map viewpoint and identify layers on tap val mapViewProxy = MapViewProxy()
// Graphic to represent the starting point of the downstream trace private val startingLocationGraphic = Graphic( symbol = SimpleMarkerSymbol( style = SimpleMarkerSymbolStyle.Cross, color = Color.green, size = 25f ) )
// Overlay to show the starting location for tracing val graphicsOverlay = GraphicsOverlay(listOf(startingLocationGraphic))
// The utility network used for tracing private val utilityNetwork: UtilityNetwork get() = arcGISMap.utilityNetworks.first()
// ServiceGeodatabase from the utility network, used for switching to a new version private var serviceGeodatabase: ServiceGeodatabase? = null
// Parameters for a downstream trace private var traceParameters: UtilityTraceParameters? = null
// Track the state of utility network capabilities private val _canGetState = MutableStateFlow(false) val canGetState = _canGetState.asStateFlow()
// Track the state of utility network topology private val _canTrace = MutableStateFlow(false) val canTrace = _canTrace.asStateFlow()
// Track the state when we have dirty areas or errors private val _canValidateNetworkTopology = MutableStateFlow(false) val canValidateNetworkTopology = _canValidateNetworkTopology.asStateFlow()
// Track the state when selections can be cleared from map private val _canClearSelection = MutableStateFlow(false) val canClearSelection = _canClearSelection.asStateFlow()
// A collapsable status message to display in the UI private val _statusMessage = MutableStateFlow("") val statusMessage = _statusMessage.asStateFlow()
// Currently selected feature that the user is editing private val _selectedFeature = MutableStateFlow<ArcGISFeature?>(null) val selectedFeature = _selectedFeature.asStateFlow()
// Field being edited on the selected feature (e.g. "devicestatus" or "nominalvoltage") private var selectedField: Field? = null
// List of coded values from the above field's domain private val _fieldValueOptions = MutableStateFlow<List<CodedValue>>(emptyList()) val fieldValueOptions = _fieldValueOptions.asStateFlow()
// Selected field coded value from the domain private val _selectedFieldValue = MutableStateFlow<CodedValue?>(null) val selectedFieldValue = _selectedFieldValue.asStateFlow()
// Keep track of the current visible area to validate network topology private val _currentVisibleArea = MutableStateFlow(Envelope(Point(0.0, 0.0), Point(0.0, 0.0)))
/** * Add credentials and loads the map & utility network. Then creates & switches to a * new version for editing. Sets up the default trace parameters and adds the dirty area * table as a feature layer to the map. Sets the button states based on * utility network capabilities. */ suspend fun initialize() { // Authenticate and load ArcGIS map setupMap() // Load utility network, and switch to a new version to allow edits setupUtilityNetwork() // Set up the default trace parameters (downstream) setupTraceParameters() // Check capabilities from the network definition to enable/disable relevant UI. setButtonStatesFromCapabilities() // Display contextual hint _statusMessage.value = INIT_STATUS_MESSAGE }
/** * Authenticate and load map. */ private suspend fun setupMap() { ArcGISEnvironment.apply { applicationContext = getApplication<Application>().applicationContext authenticationManager.arcGISAuthenticationChallengeHandler = getAuthChallengeHandler() } // Load the Naperville electric web-map arcGISMap.load().onFailure { handleError( title = "Error loading the web-map: ${it.message}", description = it.cause.toString() ) } }
/** * Create a new version and switch to allow for attribute editing. */ private suspend fun setupUtilityNetwork() { // Load the utility network associated with the web-map utilityNetwork.load().onFailure { handleError( title = "Error loading the utility network: ${it.message}", description = it.cause.toString() ) } // Construct version parameters val parameters = ServiceVersionParameters().apply { name = "ValidateNetworkTopology_${UUID.randomUUID()}" description = "Validate network topology with ArcGIS Maps SDK." access = VersionAccess.Private } // Retrieve the service geodatabase from the utility network serviceGeodatabase = utilityNetwork.serviceGeodatabase?.apply { // Load the service geodatabase load().onFailure { return handleError("Error loading service geodatabase: ${it.message}") } // Create a new private service version val versionInfo = createVersion(newVersion = parameters).getOrElse { return handleError("Unable to create version", "${it.message}") } // Switch the service geodatabase to the newly created version switchVersion(versionName = versionInfo.name).onFailure { return handleError("Failed to switch to version", "${it.message}") } } // Add the dirty area table to the map to visualize it utilityNetwork.dirtyAreaTable?.let { dirtyAreaTable -> arcGISMap.operationalLayers.add( element = FeatureLayer.createWithFeatureTable(dirtyAreaTable) ) } // Add labels to the map to visualize attribute editing addLabels( layerName = DEVICE_TABLE_NAME, fieldName = DEVICE_STATUS_FIELD, textColor = Color.blue ) addLabels( layerName = LINE_TABLE_NAME, fieldName = NOMINAL_VOLTAGE_FIELD, textColor = Color.red ) }
/** * Downstream trace parameters from a known device location, * stopping traversal on an open device. */ private suspend fun setupTraceParameters() { // Get the definition of the utility network val networkDefinition = utilityNetwork.definition ?: return // Look up the network source by its table name val utilityNetworkSource = networkDefinition.networkSources.value.first { it.name == DEVICE_TABLE_NAME } // Get the asset group val circuitBreakerGroup = utilityNetworkSource.assetGroups.first { it.name == "Circuit Breaker" } // Get the asset type val threePhaseType = circuitBreakerGroup.assetTypes.first { it.name == "Three Phase" } // Create the element for the known globalID val startingElement = utilityNetwork.createElementOrNull( assetType = threePhaseType, globalId = STARTING_LOCATION_GLOBAL_ID )?.apply { // Find the "Load" terminal terminal = threePhaseType.terminalConfiguration?.terminals?.first { it.name == "Load" } } ?: return handleError("Error creating utility network element") // Convert the utility element to an ArcGIS feature val startingFeature = utilityNetwork.getFeaturesForElements( elements = listOf(startingElement) ).getOrNull()?.firstOrNull() // Add a graphic to indicate the location on the map startingLocationGraphic.geometry = startingFeature?.geometry // Get the utility domain network val domainNetwork = networkDefinition.getDomainNetwork("ElectricDistribution") ?: return // Get the utility tier object val mediumVoltageRadial = domainNetwork.getTier("Medium Voltage Radial") ?: return // Create trace parameters for a downstream trace from the element traceParameters = UtilityTraceParameters( traceType = UtilityTraceType.Downstream, startingLocations = listOf(startingElement) ).apply { // Use the same trace config from the utility tier traceConfiguration = mediumVoltageRadial.getDefaultTraceConfiguration() } }
/** * Enable or disable the main action buttons based on the network definition's capabilities. */ private fun setButtonStatesFromCapabilities() { utilityNetwork.definition?.capabilities?.apply { _canGetState.value = supportsNetworkState _canTrace.value = supportsTrace _canValidateNetworkTopology.value = supportsValidateNetworkTopology } }
/** * Adds labels for a given field name to a layer with a given name. */ private fun addLabels(layerName: String, fieldName: String, textColor: Color) { // Create a expression for the label using the given field name val expression = SimpleLabelExpression(simpleExpression = "[$fieldName]") // Create a symbol for label's text using the given color val symbol = TextSymbol().apply { color = textColor size = 12f haloColor = Color.white haloWidth = 2f } // Create the definition from the expression and text symbol val definition = LabelDefinition(labelExpression = expression, textSymbol = symbol) // Add the definition to the map layer with the given layer name. val layer = arcGISMap.operationalLayers.first { it.name == layerName } as FeatureLayer layer.labelDefinitions.add(definition) layer.labelsEnabled = true }
/** * Gets the current state of the utility network (hasDirtyAreas, hasErrors, isNetworkTopologyEnabled). */ fun getState() { _statusMessage.value = "Getting utility network state…" viewModelScope.launch { val networkState = utilityNetwork.getState().getOrElse { return@launch handleError("Get state failed", it.message.toString()) } // Update to true if there are unsaved changes or errors in the utility network state _canValidateNetworkTopology.value = networkState.hasDirtyAreas || networkState.hasErrors // Update trace availability _canTrace.value = networkState.isNetworkTopologyEnabled // Update contextual hint val tip = if (_canValidateNetworkTopology.value) { "Tap Validate before trace or expect a trace error." } else { "Tap on a feature to edit, or tap Trace." } _statusMessage.value = buildString { appendLine("Utility Network State:") appendLine("Has dirty areas: ${networkState.hasDirtyAreas}") appendLine("Has errors: ${networkState.hasErrors}") appendLine("Network topology enabled: ${networkState.isNetworkTopologyEnabled}") append(tip) } } }
/** * Validates the utility network topology in the visible map extent to check * for check dirty areas and identify errors in the network topology. */ fun validateNetworkTopology() { _statusMessage.value = "Validating utility network topology…" // Create and start the utility network validation job using the current visible extent val utilityNetworkValidationJob = utilityNetwork.validateNetworkTopology( extent = _currentVisibleArea.value, executionType = GeoprocessingExecutionType.SynchronousExecute ).also { job -> job.start() } viewModelScope.launch { // Retrieve the result from the job val validationResult = utilityNetworkValidationJob.result().getOrElse { return@launch handleError("Validation job error: ${it.message}") } // After validation, check if dirty areas remain. _canValidateNetworkTopology.value = validationResult.hasDirtyAreas _statusMessage.value = buildString { appendLine("Network Validation Result") appendLine("Has dirty areas: ${validationResult.hasDirtyAreas}") appendLine("Has errors: ${validationResult.hasErrors}") append("Tap 'Get State' to check the updated network state.") } } }
/** * Identify a single feature from the [screenCoordinate], check if belongs to the * device or line layer, get the coded-value domain from it's field to allow editing. */ fun identifyFeatureAt( screenCoordinate: ScreenCoordinate, selectedFieldAlias: (String) -> Unit ) { viewModelScope.launch { // Perform an identify operation at the given screen coords val identifyLayerResults = mapViewProxy.identifyLayers( screenCoordinate = screenCoordinate, tolerance = IDENTIFY_TOLERANCE.dp, returnPopupsOnly = false, maximumResults = 1 ).getOrElse { return@launch handleError("Select feature failed: ${it.message}") } // Find the first result from identify results for device/line layers val identifyLayerResult = identifyLayerResults.firstOrNull { layerResult -> val layerName = layerResult.layerContent.name layerName == DEVICE_TABLE_NAME || layerName == LINE_TABLE_NAME } // Find the first feature from results val foundFeature = identifyLayerResult?.geoElements?.firstOrNull() as? ArcGISFeature // Return if no feature was identified if (foundFeature == null) { _statusMessage.value = "No feature identified. Tap in the device or line layer." return@launch } // Find the coded-value domain field to edit val (fieldName, fieldAlias) = when (foundFeature.featureTable?.tableName) { DEVICE_TABLE_NAME -> DEVICE_STATUS_FIELD to "Device status" LINE_TABLE_NAME -> NOMINAL_VOLTAGE_FIELD to "Nominal voltage" else -> null to null } if (fieldName == null) { _statusMessage.value = "Selected feature is not editable." return@launch } // Retrieve the field from the feature table val tableField = foundFeature.featureTable?.fields?.firstOrNull { it.name == fieldName } ?: return@launch handleError("Field '$fieldName' not found in feature table.") // Obtain the list of coded value fields in the selected feature val codedValues = (tableField.domain as? CodedValueDomain)?.codedValues ?: emptyList() // Update the currently selected field that the user is editing selectedField = tableField // Update the list of field value options of the selected feature _fieldValueOptions.value = codedValues // Retrieve the currently selected attribute _selectedFieldValue.value = codedValues.find { codedValue -> codedValue.code == foundFeature.attributes[fieldName] } // Clear any previous selections clearLayerSelections() // Select the identified feature on its layer (foundFeature.featureTable?.layer as? FeatureLayer)?.selectFeature(foundFeature) // Set the viewpoint to the selected feature foundFeature.geometry?.let { mapViewProxy.setViewpointGeometry(it, 20.0) } // Update the currently selected feature that the user is editing _selectedFeature.value = foundFeature // Update UI with selected feature info _statusMessage.value = "Select a new '$fieldAlias' value, then tap Apply." _canClearSelection.value = true selectedFieldAlias(fieldAlias.toString()) } }
/** * Run a simple downstream trace from the previously configured trace parameters. * Then select any features found by the trace. */ fun trace() { _statusMessage.value = "Running a downstream trace…" viewModelScope.launch { // Clear previous selections clearLayerSelections() // Get the trace params val params = traceParameters ?: return@launch handleError("Trace parameters not set.") // Run trace, and obtain results, if errors/dirty areas are found the trace will fail val traceResults = utilityNetwork.trace(params).getOrElse { return@launch handleError("Trace failed", it.message + "\n" + it.cause) } // Get the first trace element result val elementTraceResult = traceResults.firstOrNull { it is UtilityElementTraceResult } as? UtilityElementTraceResult ?: return@launch // Group elements by which layer/table they belong to and select them. selectTraceResultElements(elementTraceResult.elements) // Update contextual hint _statusMessage.value = "Trace completed:" + "${elementTraceResult.elements.size} elements found." } }
/** * Select all features that match the given list of utility elements found by the trace. */ private suspend fun selectTraceResultElements(elements: List<UtilityElement>) { // Ensure the result is not empty if (elements.isEmpty()) return handleError("No elements found in the trace result") // Find the matching feature's geometry of each utility element in all layers arcGISMap.operationalLayers.filterIsInstance<FeatureLayer>() .forEach { featureLayer -> // Clear previous selection featureLayer.clearSelection() // Used to calculate the viewpoint result val params = QueryParameters().apply { returnGeometry = true } // Create query parameters to find features who's network source name matches the layer's feature table name elements.filter { it.networkSource.name == featureLayer.featureTable?.tableName } .forEach { utilityElement -> params.objectIds.add(utilityElement.objectId) } // Check if any trace results were added from the above filter if (params.objectIds.isNotEmpty()) { // Select features that match the query val featureQueryResult = featureLayer.selectFeatures( parameters = params, mode = SelectionMode.New ).getOrElse { return handleError( title = it.message.toString(), description = it.cause.toString() ) } // Create list of all the feature result geometries val resultGeometryList = mutableListOf<Geometry>() featureQueryResult.iterator().forEach { feature -> feature.geometry?.let { resultGeometryList.add(it) } } // Obtain the union geometry of all the feature geometries GeometryEngine.unionOrNull(resultGeometryList)?.let { unionGeometry -> // Set the map's viewpoint to the union result geometry mapViewProxy.setViewpointAnimated(Viewpoint(boundingGeometry = unionGeometry)) } } } _canClearSelection.value = true }
/** * Update the feature with the new coded value and apply the edit to the feature service. */ fun applyEdits() { _statusMessage.value = "Applying edits…" // Get the selected feature to update val feature = _selectedFeature.value ?: return // Get the table which related to the feature val serviceFeatureTable = feature.featureTable as? ServiceFeatureTable ?: return handleError("Feature is not from a service feature table.") // Get the selected field value coded value val newCode = _selectedFieldValue.value?.code ?: return handleError("No new coded value selected.") // Update the feature's attribute val fieldName = selectedField?.name ?: return feature.attributes[fieldName] = newCode // Apply edits and handle results viewModelScope.launch { // Update the backing service feature table serviceFeatureTable.updateFeature(feature).onFailure { return@launch handleError("Failed to update feature", it.message + "\n" + it.cause) } // Apply all local edits in all tables to the service geodatabase val editResults = serviceGeodatabase?.applyEdits()?.getOrElse { return@launch handleError("Apply edits failed: ${it.message}") } // Check for any feature edit errors val hadErrors = editResults?.any { tableEditResult -> tableEditResult.editResults.any { featureEditResult -> featureEditResult.completedWithErrors } } ?: true if (hadErrors) _statusMessage.value = "Apply edits completed with error(s)." else _statusMessage.value = "Edits applied successfully.\n" + "Tap 'Get State' to check the updated network state." // Once edits are applied, enable to validate the network again. _canValidateNetworkTopology.value = true } }
/** * Clears any selected features being edited on the map. */ fun clearFeatureEditSelection() { clearLayerSelections() _selectedFeature.value = null selectedField = null _fieldValueOptions.value = emptyList() _selectedFieldValue.value = null _canClearSelection.value = false _statusMessage.value = INIT_STATUS_MESSAGE }
/** * Clear the selection on all feature layers in the map. */ private fun clearLayerSelections() { arcGISMap.operationalLayers.filterIsInstance<FeatureLayer>().forEach { layer -> layer.clearSelection() } }
/** * Update the currently selected field value */ fun updateSelectedValue(codedValue: CodedValue) { _selectedFieldValue.value = codedValue }
/** * Update the currently visible extent */ fun updateVisibleArea(polygon: Polygon) { _currentVisibleArea.value = polygon.extent }
// Message dialog for errors val messageDialogVM = MessageDialogViewModel()
/** * Display error and reset */ private fun handleError(title: String, description: String = "") { reset() messageDialogVM.showMessageDialog(title, description) }
/** * Resets the trace, removing graphics and clearing selections. */ private fun reset() { arcGISMap.operationalLayers .filterIsInstance<FeatureLayer>() .forEach { it.clearSelection() } graphicsOverlay.graphics.clear() _canTrace.value = false }
companion object { // Public credentials for the data in this sample (Editor user) const val USERNAME = "editor01" const val PASSWORD = "S7#i2LWmYH75"
// The Naperville electric web map on sample server 7 private const val NAPERVILLE_ELECTRIC_WEBMAP_ITEM_ID = "6e3fc6db3d0b4e6589eb4097eb3e5b9b" private const val SAMPLE_SERVER_7_PORTAL = "https://sampleserver7.arcgisonline.com/portal/"
// The relevant table names/fields in Naperville electric private const val DEVICE_TABLE_NAME = "Electric Distribution Device" private const val DEVICE_STATUS_FIELD = "devicestatus" private const val LINE_TABLE_NAME = "Electric Distribution Line" private const val NOMINAL_VOLTAGE_FIELD = "nominalvoltage"
// The known device's global ID used for the default starting location private val STARTING_LOCATION_GLOBAL_ID = Guid("1CAF7740-0BF4-4113-8DB2-654E18800028")
// Tolerance in device-independent pixels for identify private const val IDENTIFY_TOLERANCE = 10f
private const val INIT_STATUS_MESSAGE = "Utility network loaded.\n" + "Tap on a feature to edit.\n" + "Tap on 'Get State' to check if validating is necessary or if tracing is available.\n" + "Tap 'Trace' to run a trace." }}
/** * Returns a [ArcGISAuthenticationChallengeHandler] to access the utility network URL. */private fun getAuthChallengeHandler(): ArcGISAuthenticationChallengeHandler { return ArcGISAuthenticationChallengeHandler { challenge -> val result: Result<TokenCredential> = runBlocking { TokenCredential.create(challenge.requestUrl, USERNAME, PASSWORD, 0) } if (result.getOrNull() != null) { val credential = result.getOrNull() return@ArcGISAuthenticationChallengeHandler ArcGISAuthenticationChallengeResponse .ContinueWithCredential(credential!!) } else { val ex = result.exceptionOrNull() return@ArcGISAuthenticationChallengeHandler ArcGISAuthenticationChallengeResponse .ContinueAndFailWithError(ex!!) } }}
private val Color.Companion.blue: Color get() { return fromRgba(0, 0, 255, 255) }