Display clusters

View on GitHubSample viewer app

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: Feature reduction map

Popup message displaying the cluster details: Cluster details popup

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

  1. Create a map from a web map PortalItem.
  2. Get the cluster enabled layer from the map's operational layers.
  3. Get the FeatureReduction from the feature layer and set isEnabled value to enable or disable clustering on the feature layer.
  4. When the user clicks on the map, call identifyLayers and pass in the map's screen coordinates.
  5. Get the Popup and the corresponding PopupElement from the resulting IdentifyLayerResult and use it to construct a popup output string.
  6. 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

MapViewModel.ktMapViewModel.ktMainActivity.ktClusterInfoContent.ktMainScreen.kt
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/* 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
                )
            }
        }
    }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.