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
FeatureReduction
from the feature layer and setisEnabled
value to enable or disable clustering on the feature layer. - When the user clicks on the map, call
identifyLayers
and pass in the map's screen coordinates. - Get the
Popup
and the correspondingPopupElement
from the resultingIdentifyLayerResult
and use it to construct a popup output string. - Use
Html.fromHtml
to 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.components
import android.app.Application
import android.graphics.Typeface
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.text.style.UnderlineSpan
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.core.text.HtmlCompat
import androidx.lifecycle.AndroidViewModel
import com.arcgismaps.LoadStatus
import com.arcgismaps.mapping.ArcGISMap
import com.arcgismaps.mapping.BasemapStyle
import com.arcgismaps.mapping.PortalItem
import com.arcgismaps.mapping.Viewpoint
import com.arcgismaps.mapping.layers.FeatureLayer
import com.arcgismaps.mapping.popup.FieldsPopupElement
import com.arcgismaps.mapping.popup.TextPopupElement
import com.arcgismaps.mapping.view.IdentifyLayerResult
import com.arcgismaps.mapping.view.SingleTapConfirmedEvent
import com.arcgismaps.portal.Portal
import com.arcgismaps.toolkit.geoviewcompose.MapViewProxy
import com.esri.arcgismaps.sample.displayclusters.R
import com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModel
import kotlinx.coroutines.CoroutineScope
import 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
)
}
}
}
}