Clip a field function to a changing area of interest within the map view and automatically update the analysis as the map is navigated.

Use case
Spatial analysis workflows may only need to process the area currently being viewed or investigated. For example, a suitability analysis might evaluate potential locations within a specific area of interest rather than across the full extent of the input data. A clip field function can restrict the analysis to that area and update the clip extent dynamically as the area of interest changes.
Updating the clip extent does not require the analysis to be rebuilt. Restricting the field function to a smaller extent can also reduce unnecessary processing and improve performance, particularly on devices with limited graphics processing resources. Note that analysis is performed at the full resolution of the source data.
How to use the sample
When the sample opens, the map displays elevation within a clipped extent centred on the map view. The clipped analysis area covers 60 percent of the visible extent and is outlined on the map. Pan or zoom the map to explore different parts of the elevation dataset. As the viewpoint changes, the analysis area moves with the map view and the field function is clipped to the new extent. Use the Settings pane to adjust the minimum and maximum elevation values displayed by the analysis. The analysis updates automatically to display elevation values within the selected range and clips them to the current analysis area.
How it works
- Create an
AnalysisOverlayand aGraphicsOverlay, then add both overlays to the map view. - Create a
ContinuousFieldfrom an elevation raster file usingContinuousField.createFromFiles. - Create a
ContinuousFieldFunctionfrom the continuous field usingContinuousFieldSupplier. - Create two
FloatSupplierinstances to provide the minimum and maximum elevation values. - Create a
BooleanFieldFunctionthat identifies elevation values within the supplied range usingisGreaterThanOrEqualTo,isLessThanOrEqualTo, and the infix functionand. - Apply the boolean selection to the continuous field function using
maskto retain only elevation values within the selected range. - Create a
ContinuousFieldClipFunctionfrom the masked elevation function. - Create a
FieldAnalysisfrom the clip function using theFieldAnalysisconstructor that takes aContinuousFieldFunctionand aStretchRenderer. - Add the field analysis to the analysis overlay.
- Listen for changes to the visible area of the
MapViewusingonVisibleAreaChanged. - Create an
Envelopethat’s centered in the current visible area, but with edges inset to cover just 60 percent of the visible extent. - Update the clip extent graphic and set the
ContinuousFieldClipFunction.extentproperty to the resulting envelope. - Update the float suppliers’
valueproperties whenever minimum and maximum elevation settings are changed, to update the analysis result dynamically.
Relevant API
- AnalysisOverlay
- BooleanFieldFunction
- ColorRamp
- ContinuousField
- ContinuousFieldClipFunction
- ContinuousFieldFunction
- ContinuousFieldSupplier
- FieldAnalysis
- FloatSupplier
- StretchRenderer
Offline data
The sample uses a 10m resolution digital terrain elevation raster of the Isle of Arran, Scotland (Data Copyright Scottish Government and SEPA (2014)). It is downloaded from ArcGIS Online automatically.
Tags
clip, elevation, extent, map algebra, raster, spatial analysis, terrain
Sample code
/* Copyright 2026 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.clipafieldfunctiontomapviewextent.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.Colorimport com.arcgismaps.analysis.ContinuousFieldimport com.arcgismaps.analysis.ContinuousFieldClipFunctionimport com.arcgismaps.analysis.ContinuousFieldSupplierimport com.arcgismaps.analysis.FloatSupplierimport com.arcgismaps.analysis.interactive.FieldAnalysisimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.Geometryimport com.arcgismaps.geometry.GeometryEngineimport com.arcgismaps.geometry.Polygonimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.BasemapStyleimport com.arcgismaps.mapping.symbology.SimpleFillSymbolimport com.arcgismaps.mapping.symbology.SimpleFillSymbolStyleimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.raster.ColorRampimport com.arcgismaps.mapping.symbology.raster.MinMaxStretchParametersimport com.arcgismaps.mapping.symbology.raster.PresetColorRampTypeimport com.arcgismaps.mapping.symbology.raster.StretchRendererimport com.arcgismaps.mapping.view.AnalysisOverlayimport com.arcgismaps.mapping.view.AnalysisViewStatusimport com.arcgismaps.mapping.view.GeoViewimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.toolkit.geoviewcompose.MapViewProxyimport com.esri.arcgismaps.sample.clipafieldfunctiontomapviewextent.Rimport com.esri.arcgismaps.sample.clipafieldfunctiontomapviewextent.components.ClipFunctionUiState.Companion.initialClipFunctionUiStateimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModelimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launchimport java.io.File
const val CLIP_VISIBLE_EXTENT_FRACTION = 0.6const val MINIMUM_ELEVATION_METERS = 0.0fconst val MAXIMUM_ELEVATION_METERS = 874.0f
class ClipAFieldFunctionToMapViewExtentViewModel(app: Application) : AndroidViewModel(app) { // Create a state flow to hold the UI state for the supporting pane controls private val _clipFunctionUiState = MutableStateFlow(initialClipFunctionUiState)
// Expose the state flow as read-only for the UI val uiState = _clipFunctionUiState.asStateFlow()
// Create a MapViewProxy, used to set viewpoint val mapViewProxy = MapViewProxy()
// Initialize and keep track of the ArcGISMap & the overlays it uses val arcGISMap by mutableStateOf(ArcGISMap(BasemapStyle.ArcGISTopographic)) val analysisOverlay by mutableStateOf(AnalysisOverlay()) val graphicsOverlay by mutableStateOf(GraphicsOverlay())
// Indicates when the ProgressIndicator should be displayed var displayProgressIndicator by mutableStateOf(false) private set
// Create a message dialog view model for handling error messages val messageDialogVM = MessageDialogViewModel()
// Location of file containing elevation data private val provisionPath: String by lazy { app.getExternalFilesDir(null)?.path + File.separator + app.getString( R.string.clip_a_field_function_to_map_view_extent_app_name ) + File.separator } private val filePath = provisionPath + "arran.tif"
// Elevation range suppliers private val minimumElevationSupplier = FloatSupplier(MINIMUM_ELEVATION_METERS) private val maximumElevationSupplier = FloatSupplier(MAXIMUM_ELEVATION_METERS)
// Variables that are initialized in the init block and referenced in event listener(s) private lateinit var elevationField: ContinuousField private lateinit var continuousFieldClipFunction: ContinuousFieldClipFunction private lateinit var fieldAnalysis: FieldAnalysis
// Stretch renderer for visualizing the elevation private val stretchRenderer = StretchRenderer( parameters = MinMaxStretchParameters( minValues = listOf(MINIMUM_ELEVATION_METERS.toDouble()), maxValues = listOf(MAXIMUM_ELEVATION_METERS.toDouble()) ), gammas = listOf(1.0), estimateStatistics = false, colorRamp = ColorRamp.create( type = PresetColorRampType.Surface, size = 256 ) )
// Graphic used to show the clip extent private val clipExtentGraphic = Graphic( symbol = SimpleFillSymbol( style = SimpleFillSymbolStyle.Null, outline = SimpleLineSymbol( color = Color.fromRgba(r = 78, g = 50, b = 50, a = 255), width = 1f ) ) )
init { // Add clip extent graphic to the graphics overlay graphicsOverlay.graphics.add(clipExtentGraphic)
viewModelScope.launch { // Load the map and handle any errors by showing a message dialog arcGISMap.load().getOrElse { error -> messageDialogVM.showMessageDialog(error) return@launch }
// Create a ContinuousField from a raster file containing elevation data elevationField = ContinuousField.createFromFiles(filePaths = listOf(filePath), band = 0) .getOrElse { error -> messageDialogVM.showMessageDialog(error) return@launch }
// Create a continuous field function from the elevation field val continuousFieldFunction = ContinuousFieldSupplier(elevationField)
// Create a boolean field function for the elevation range with map algebra val elevationSelection = continuousFieldFunction.isGreaterThanOrEqualTo(minimumElevationSupplier) and continuousFieldFunction.isLessThanOrEqualTo(maximumElevationSupplier)
// Mask the elevation field using the boolean field function to create the masked // elevation function val maskedElevationFunction = continuousFieldFunction.mask(elevationSelection)
// Create the continuous field clip function using the masked elevation function. Use // null initially for the extent, which will be updated later based on the map view // visible area. continuousFieldClipFunction = ContinuousFieldClipFunction( field = maskedElevationFunction, extent = null )
// Create the field analysis using the continuous field clip function and add it to the // analysis overlay fieldAnalysis = FieldAnalysis(continuousFieldClipFunction, stretchRenderer) fieldAnalysis.opacity = 0.7f fieldAnalysis.isVisible = false // made visible in onVisibleAreaChanged() analysisOverlay.analyses.add(fieldAnalysis)
// Set the viewpoint of the map to the center of the elevation field's extent mapViewProxy.setViewpointCenter( center = elevationField.extent.center, scale = 150000.0 ) } }
/** * An AnalysisViewStatus listener that displays the progress indicator when the status of the * analysis is Updating and hides it otherwise. Also displays details of any error that occurs * when the analysis is displayed. */ fun analysisViewStatusListener(event: GeoView.GeoViewAnalysisViewStatusChanged) { when (val status = event.analysisViewStatus) { is AnalysisViewStatus.Error -> { messageDialogVM.showMessageDialog( throwable = status.details ) displayProgressIndicator = false } AnalysisViewStatus.UpToDate -> { displayProgressIndicator = false } AnalysisViewStatus.Updating -> { displayProgressIndicator = true } } }
/** * Updates the minimum elevation and maximum elevation values. */ fun onMinMaxElevationChange(minimumElevation: Float, maximumElevation: Float) { _clipFunctionUiState.update { it.copy(minimumElevation = minimumElevation, maximumElevation = maximumElevation) } minimumElevationSupplier.value = minimumElevation maximumElevationSupplier.value = maximumElevation }
/** * Listener called when the visible area of the MapView has changed. Calculates a clip geometry * based on the new [visibleArea], and uses it to update continuousFieldClipFunction's extent * and the graphic that's used to show the current clip extent. */ fun onVisibleAreaChanged(visibleArea: Polygon) { // Just return if initialization not complete yet if (!::fieldAnalysis.isInitialized) { return }
// Build the clip geometry based on the new visible area extent val clipGeometry = buildClipGeometry(visibleArea.extent)
// If no overlap between the visible area and the elevation field, hide the analysis and the // clip extent graphic, so stale results are not displayed if (clipGeometry == null) { clipExtentGraphic.isVisible = false fieldAnalysis.isVisible = false displayProgressIndicator = false return }
// Update the graphic used to show the current clip extent clipExtentGraphic.geometry = clipGeometry
// Update the clip function's extent based on the new clip geometry continuousFieldClipFunction.extent = clipGeometry.extent fieldAnalysis.isVisible = true clipExtentGraphic.isVisible = true }
/** * Calculates a clip geometry based on the given [visibleExtent]. Returns the intersection * between that and the extent of the elevation field, or null if there is no intersection. */ private fun buildClipGeometry(visibleExtent: Envelope) : Geometry? { // Get the extent of the elevation field val elevationFieldExtent = elevationField.extent
// Generate an inset extent based on the visible extent and the clip fraction val insetExtent = Envelope( center = visibleExtent.center, width = visibleExtent.width * CLIP_VISIBLE_EXTENT_FRACTION, height = visibleExtent.height * CLIP_VISIBLE_EXTENT_FRACTION )
// Ensure the inset extent is within the elevation field's extent val intersection = GeometryEngine.intersectionOrNull( geometry1 = insetExtent, geometry2 = elevationFieldExtent ) return when { intersection == null -> null intersection.isEmpty -> null else -> intersection } }}
data class ClipFunctionUiState( val minimumElevation: Float, val maximumElevation: Float) { companion object { // Initial parameters to drive the UI on launch val initialClipFunctionUiState = ClipFunctionUiState( minimumElevation = MINIMUM_ELEVATION_METERS, maximumElevation = MAXIMUM_ELEVATION_METERS ) }}/* Copyright 2026 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.clipafieldfunctiontomapviewextent
import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Surfaceimport com.esri.arcgismaps.sample.clipafieldfunctiontomapviewextent.screens.ClipAFieldFunctionToMapViewExtentScreenimport com.esri.arcgismaps.sample.sampleslib.theme.SampleAppTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { SampleAppTheme { Surface(color = MaterialTheme.colorScheme.background) { ClipAFieldFunctionToMapViewExtentScreen() } } } }}/* Copyright 2026 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.clipafieldfunctiontomapviewextent.screens
import androidx.compose.animation.animateContentSizeimport androidx.compose.foundation.layout.BoxScopeimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Modifierimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.text.style.TextAlignimport androidx.lifecycle.compose.collectAsStateWithLifecycleimport androidx.lifecycle.viewmodel.compose.viewModelimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.esri.arcgismaps.sample.clipafieldfunctiontomapviewextent.Rimport com.esri.arcgismaps.sample.clipafieldfunctiontomapviewextent.components.ClipAFieldFunctionToMapViewExtentViewModelimport com.esri.arcgismaps.sample.clipafieldfunctiontomapviewextent.components.ClipFunctionUiStateimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogimport com.esri.arcgismaps.sample.sampleslib.components.SampleDeviceLightDarkPreviewimport com.esri.arcgismaps.sample.sampleslib.components.SamplePreviewSurfaceimport com.esri.arcgismaps.sample.sampleslib.components.SampleTopAppBarimport com.esri.arcgismaps.sample.sampleslib.components.adaptive.AdaptiveThreePaneimport com.esri.arcgismaps.sample.sampleslib.components.adaptive.ThreePaneConfig
/** * Main composable screen for the sample. * It owns the ViewModel and hoists UI state for the scaffold and the MapView. */@Composablefun ClipAFieldFunctionToMapViewExtentScreen( viewModel: ClipAFieldFunctionToMapViewExtentViewModel = viewModel()) { val uiState = viewModel.uiState.collectAsStateWithLifecycle().value
MainScreenScaffold( uiState = uiState, displayProgressIndicator = viewModel.displayProgressIndicator, onMinMaxElevationChange = viewModel::onMinMaxElevationChange, mainPaneContent = { MapView( modifier = Modifier .fillMaxSize() .animateContentSize(), arcGISMap = viewModel.arcGISMap, mapViewProxy = viewModel.mapViewProxy, analysisOverlays = listOf(viewModel.analysisOverlay), graphicsOverlays = listOf(viewModel.graphicsOverlay), onVisibleAreaChanged = viewModel::onVisibleAreaChanged, onAnalysisViewStatusChanged = viewModel::analysisViewStatusListener ) RasterDataCopyrightText() // displays on top of the MapView } )
viewModel.messageDialogVM.apply { if (dialogStatus) { MessageDialog( title = messageTitle, description = messageDescription, onDismissRequest = ::dismissDialog ) } }}
@Composableprivate fun MainScreenScaffold( uiState: ClipFunctionUiState, displayProgressIndicator: Boolean, onMinMaxElevationChange: (Float, Float) -> Unit, mainPaneContent: @Composable BoxScope.() -> Unit) { Scaffold( topBar = { SampleTopAppBar(title = stringResource(R.string.clip_a_field_function_to_map_view_extent_app_name)) }, content = { paddingValues -> AdaptiveThreePane( modifier = Modifier .fillMaxSize() .padding(paddingValues), supportingPaneTitle = "Settings", config = ThreePaneConfig(compactSupportingPaneHeightRatio = 0.31f), mainPane = { _, _ -> mainPaneContent() }, supportingPane = { _, _ -> ClipAFieldFunctionToMapViewExtentSupportingPane( uiState = uiState, displayProgressIndicator = displayProgressIndicator, onMinMaxElevationChange = onMinMaxElevationChange ) } ) } )}
/** * Displays copyright text for the sample's source raster. */@Composableprivate fun RasterDataCopyrightText() { Text( text = "Raster data copyright Scottish Government and SEPA (2014)", style = MaterialTheme.typography.labelSmall, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth() )}
@SampleDeviceLightDarkPreview@Composableprivate fun MainScreenPreview() { SamplePreviewSurface { MainScreenScaffold( uiState = ClipFunctionUiState.initialClipFunctionUiState, displayProgressIndicator = true, onMinMaxElevationChange = { _, _ -> }, mainPaneContent = {} ) }}/* Copyright 2026 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.clipafieldfunctiontomapviewextent.screens
import androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.sizeimport androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.RangeSliderimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Modifierimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.unit.dpimport com.esri.arcgismaps.sample.clipafieldfunctiontomapviewextent.components.ClipFunctionUiStateimport com.esri.arcgismaps.sample.clipafieldfunctiontomapviewextent.components.MAXIMUM_ELEVATION_METERSimport com.esri.arcgismaps.sample.clipafieldfunctiontomapviewextent.components.MINIMUM_ELEVATION_METERS
/** * Supporting pane content for the sample. */@Composableinternal fun ClipAFieldFunctionToMapViewExtentSupportingPane( uiState: ClipFunctionUiState, displayProgressIndicator: Boolean, onMinMaxElevationChange: (Float, Float) -> Unit) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { val message = when (displayProgressIndicator) { false -> "Analysis up to date" true -> "Analysis updating..." } Text(text = message) if (displayProgressIndicator) { CircularProgressIndicator(modifier = Modifier.size(20.dp)) } } Text( text = "Elevation range: ${uiState.minimumElevation.toInt()} to ${uiState.maximumElevation.toInt()} m", modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center ) RangeSlider( modifier = Modifier.fillMaxWidth(), value = uiState.minimumElevation..uiState.maximumElevation, onValueChange = { newRange -> if (newRange.start < newRange.endInclusive) { onMinMaxElevationChange(newRange.start, newRange.endInclusive) } }, valueRange = MINIMUM_ELEVATION_METERS..MAXIMUM_ELEVATION_METERS )}