Display a web map with a point feature layer that has feature reduction enabled to aggregate points into clusters.
Map displaying the feature layer with feature reduction property enabled by default:

Popup message displaying the cluster details:

Use case
Feature clustering can be used to dynamically aggregate groups of points that are within proximity of each other in order to represent each group with a single symbol. Such grouping allows you to see patterns in the data that are difficult to visualize when a layer contains hundreds or thousands of points that overlap and cover each other.
How to use the sample
Pan and zoom the map to view how clustering is dynamically updated. Disable clustering to view the original point features that make up the clustered elements. When clustering is On, you can click on a clustered geoelement to view aggregated information and summary statistics for that cluster. When clustering is toggled off and you click on the original feature you get access to information about individual power plant features.
How it works
- Create a map from a web map
PortalItem. - Get the cluster enabled layer from the map’s operational layers.
- Get the
FeatureReductionfrom the feature layer and setisEnabledvalue to enable or disable clustering on the feature layer. - When the user clicks on the map, call
identifyLayersand pass in the map’s screen coordinates. - Get the
Popupand the correspondingPopupElementfrom the resultingIdentifyLayerResultand use it to construct a popup output string. - Use
Html.fromHtmlto convert the html tags in the output string to a styled text and display it to the user.
Relevant API
- FeatureLayer
- FeatureReduction
- IdentifyLayerResult
- Popup
- PopupElement
- PopupField
- Portal
- PortalItem
About the data
This sample uses a web map that displays the Esri Global Power Plants feature layer with feature reduction enabled. When enabled, the aggregate features symbology shows the color of the most common power plant type, and a size relative to the average plant capacity of the cluster.
Additional information
This sample uses the GeoView-Compose Toolkit module to be able to implement a composable MapView.
Tags
aggregate, bin, cluster, geoview-compose, group, merge, normalize, reduce, summarize, toolkit
Sample Code
/* Copyright 2023 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.displayclusters
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.displayclusters.screens.MainScreen
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 { FeatureReductionApp() } } }
@Composable private fun FeatureReductionApp() { Surface( color = MaterialTheme.colorScheme.background ) { MainScreen( sampleName = getString(R.string.display_clusters_app_name) ) } }}/* Copyright 2023 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.displayclusters.components
import android.content.res.Configurationimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.rounded.Closeimport androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.Iconimport androidx.compose.material3.IconButtonimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.text.AnnotatedStringimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.esri.arcgismaps.sample.sampleslib.theme.SampleAppThemeimport com.esri.arcgismaps.sample.sampleslib.theme.SampleTypography
@Composablefun ClusterInfoContent( popupTitle: String, clusterInfoList: MutableList<AnnotatedString>, onDismiss: () -> Unit = { },) { Column(Modifier.background(MaterialTheme.colorScheme.background)) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, ) { Text( modifier = Modifier .padding(horizontal = 30.dp, vertical = 12.dp) .weight(6f), text = popupTitle, style = SampleTypography.displaySmall )
IconButton( modifier = Modifier.weight(1f), onClick = onDismiss ) { Icon( imageVector = Icons.Rounded.Close, contentDescription = "Close button" ) } }
clusterInfoList.forEach { annotatedString -> HorizontalDivider( modifier = Modifier.padding(horizontal = 12.dp), color = Color.LightGray ) Text( modifier = Modifier.padding(horizontal = 30.dp, vertical = 16.dp), text = annotatedString ) } Spacer(modifier = Modifier.size(24.dp)) }}
@Preview(showBackground = true)@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true)@Composablefun ClusterInfoContentPreview() { SampleAppTheme { ClusterInfoContent( popupTitle = "Cluster summary", clusterInfoList = mutableListOf( AnnotatedString("This is a cluster description") ) ) }}/* Copyright 2023 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.displayclusters.components
import android.app.Applicationimport android.graphics.Typefaceimport android.text.Spannedimport android.text.style.ForegroundColorSpanimport android.text.style.StyleSpanimport android.text.style.UnderlineSpanimport androidx.compose.runtime.mutableStateListOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.text.AnnotatedStringimport androidx.compose.ui.text.SpanStyleimport androidx.compose.ui.text.buildAnnotatedStringimport androidx.compose.ui.text.font.FontStyleimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.style.TextDecorationimport androidx.compose.ui.unit.dpimport androidx.core.text.HtmlCompatimport androidx.lifecycle.AndroidViewModelimport com.arcgismaps.LoadStatusimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.BasemapStyleimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.Viewpointimport com.arcgismaps.mapping.layers.FeatureLayerimport com.arcgismaps.mapping.popup.FieldsPopupElementimport com.arcgismaps.mapping.popup.TextPopupElementimport com.arcgismaps.mapping.view.IdentifyLayerResultimport com.arcgismaps.mapping.view.SingleTapConfirmedEventimport com.arcgismaps.portal.Portalimport com.arcgismaps.toolkit.geoviewcompose.MapViewProxyimport com.esri.arcgismaps.sample.displayclusters.Rimport com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModelimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launch
class MapViewModel( application: Application, private val sampleCoroutineScope: CoroutineScope) : AndroidViewModel(application) {
// create a ViewModel to handle dialog interactions val messageDialogVM: MessageDialogViewModel = MessageDialogViewModel()
// Flag indicating whether feature reduction is enabled or not val isFeatureReductionEnabled = mutableStateOf(true)
// Flag to show or dismiss the LoadingDialog val showLoadingDialog = mutableStateOf(false)
// Flag to show or dismiss the bottom sheet val showClusterSummaryBottomSheet = mutableStateOf(false)
// Initialize clusterInfoList which holds the popup details val clusterInfoList = mutableStateListOf<AnnotatedString>()
// the title of the popup result val popupTitle = mutableStateOf("")
// create a MapViewProxy that the view model will use to identify features in the MapView. // this also needs to be passed to the composable MapView() function. val mapViewProxy = MapViewProxy()
// define ArcGIS map using Night Navigation basemap var map = ArcGISMap(BasemapStyle.ArcGISNavigationNight)
init { // show loading dialog to indicate that the map is loading showLoadingDialog.value = true // load the portal and create a map from the portal item val portalItem = PortalItem( Portal(application.getString(R.string.portal_url)), "8916d50c44c746c1aafae001552bad23" ) // set the map to be displayed in the layout's MapView and set it's initialViewpoint map = ArcGISMap(portalItem).apply { initialViewpoint = Viewpoint(39.8, -98.6, 10e7) }
sampleCoroutineScope.launch { map.load().onSuccess { showLoadingDialog.value = false } } }
/** `* Toggle the FeatureLayer's featureReduction property */ fun toggleFeatureReduction() { isFeatureReductionEnabled.value = !isFeatureReductionEnabled.value if (map.loadStatus.value == LoadStatus.Loaded) { map.operationalLayers.forEach { layer -> when (layer) { is FeatureLayer -> { layer.featureReduction?.isEnabled = isFeatureReductionEnabled.value }
else -> {} } } } }
/** * Identifies the tapped screen coordinate in the provided [singleTapConfirmedEvent] */ fun identify(singleTapConfirmedEvent: SingleTapConfirmedEvent) { sampleCoroutineScope.launch { dismissBottomSheet() // call identifyLayers when a tap event occurs val identifyResult = mapViewProxy.identifyLayers(singleTapConfirmedEvent.screenCoordinate, 3.dp) handleIdentifyResult(identifyResult) } }
/** * Identify the feature layer results and display the resulting popup element information */ private fun handleIdentifyResult(result: Result<List<IdentifyLayerResult>>) { sampleCoroutineScope.launch { result.onSuccess { identifyResultList -> // initialize the string for each tap event resulting in a new identifyResultList clusterInfoList.clear() popupTitle.value = "" identifyResultList.forEach { identifyLayerResult -> val popups = identifyLayerResult.popups popups.forEach { popup -> // set the popup title popupTitle.value = popup.title // show the bottom sheet for the popup content showClusterSummaryBottomSheet.value = true popup.evaluateExpressions().onSuccess { popup.evaluatedElements.forEach { popupElement -> when (popupElement) { is FieldsPopupElement -> { popupElement.fields.forEach { popupField -> // convert popupField.label embedded with html tags using HtmlCompat.fromHtml clusterInfoList.add( HtmlCompat.fromHtml( "${popupField.label}: ${popup.getFormattedValue(popupField)}", HtmlCompat.FROM_HTML_MODE_COMPACT ).toAnnotatedString() ) } }
is TextPopupElement -> { // convert popupElement.text message embedded with html tags using HtmlCompat.fromHtml clusterInfoList.add( HtmlCompat.fromHtml( popupElement.text, HtmlCompat.FROM_HTML_MODE_COMPACT ).toAnnotatedString() ) }
else -> { clusterInfoList.add( HtmlCompat.fromHtml( "Unsupported popup element: ${popupElement.javaClass.name}", HtmlCompat.FROM_HTML_MODE_COMPACT ).toAnnotatedString() ) } } } }.onFailure { error -> messageDialogVM.showMessageDialog( title = "Error in evaluating popup expression: ${error.message.toString()}", description = error.cause.toString() ) } } } }.onFailure { error -> messageDialogVM.showMessageDialog( title = "Error in identify: ${error.message.toString()}", description = error.cause.toString() ) } } }
/** * Dismiss the bottomsheet */ fun dismissBottomSheet() { showClusterSummaryBottomSheet.value = false }
/** * Helper function which converts a [Spanned] into an [AnnotatedString] trying to keep as much formatting as possible. * [AnnotatedString] is supported in compose via the Text composable * * Currently supports `bold`, `italic`, `underline` and `color`. * More info can be found at: * https://stackoverflow.com/questions/66494838/android-compose-how-to-use-html-tags-in-a-text-view and * https://medium.com/@kevinskrei/annotated-text-in-jetpack-compose-8dc596ed62d */ private fun Spanned.toAnnotatedString(): AnnotatedString = buildAnnotatedString { val spanned = this@toAnnotatedString append(spanned.toString()) getSpans(0, spanned.length, Any::class.java).forEach { span -> val start = getSpanStart(span) val end = getSpanEnd(span) when (span) { is StyleSpan -> when (span.style) { Typeface.BOLD -> addStyle(SpanStyle(fontWeight = FontWeight.Bold), start, end) Typeface.ITALIC -> addStyle(SpanStyle(fontStyle = FontStyle.Italic), start, end) Typeface.BOLD_ITALIC -> addStyle( SpanStyle( fontWeight = FontWeight.Bold, fontStyle = FontStyle.Italic ), start, end ) }
is UnderlineSpan -> addStyle( SpanStyle(textDecoration = TextDecoration.Underline), start, end )
is ForegroundColorSpan -> addStyle( SpanStyle(color = Color(span.foregroundColor)), start, end ) } } }}/* Copyright 2023 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.displayclusters.screens
import android.app.Applicationimport androidx.compose.foundation.layout.Arrangementimport 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.material3.Scaffoldimport androidx.compose.material3.Switchimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.unit.dpimport com.arcgismaps.toolkit.geoviewcompose.MapViewimport com.esri.arcgismaps.sample.displayclusters.components.ClusterInfoContentimport com.esri.arcgismaps.sample.displayclusters.components.MapViewModelimport com.esri.arcgismaps.sample.sampleslib.components.BottomSheetimport 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.SampleTypography
/** * Main screen layout for the sample app */@Composablefun MainScreen(sampleName: String) {
// coroutineScope that will be cancelled when this call leaves the composition val sampleCoroutineScope = rememberCoroutineScope() // get the application context val application = LocalContext.current.applicationContext as Application // create a ViewModel to handle MapView interactions val mapViewModel = remember { MapViewModel(application, sampleCoroutineScope) }
Scaffold( topBar = { SampleTopAppBar(title = sampleName) }, content = { Column( modifier = Modifier .fillMaxSize() .padding(it), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { MapView( modifier = Modifier .fillMaxSize() .weight(1f), arcGISMap = mapViewModel.map, mapViewProxy = mapViewModel.mapViewProxy, onSingleTapConfirmed = mapViewModel::identify, onPan = { mapViewModel.dismissBottomSheet() } ) // Button to enable/disable featureReduction property Row( modifier = Modifier .padding(12.dp) .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = "Feature clustering", style = SampleTypography.bodyMedium ) Switch( checked = mapViewModel.isFeatureReductionEnabled.value, onCheckedChange = { mapViewModel.toggleFeatureReduction() }) }
// display a MessageDialog if the sample encounters an error mapViewModel.messageDialogVM.apply { if (dialogStatus) { MessageDialog( title = messageTitle, description = messageDescription, onDismissRequest = ::dismissDialog ) } }
// display a LoadingDialog to indicate the map loading status if (mapViewModel.showLoadingDialog.value) { LoadingDialog(loadingMessage = "Loading map...") } }
// display a bottom sheet to show popup details BottomSheet(isVisible = mapViewModel.showClusterSummaryBottomSheet.value) { ClusterInfoContent( popupTitle = mapViewModel.popupTitle.value, clusterInfoList = mapViewModel.clusterInfoList, onDismiss = { mapViewModel.dismissBottomSheet() } ) } } )}