Display clusters

View on GitHub

Display a web map with a point feature layer that has feature reduction enabled to aggregate points into clusters.

Image of display clusters

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. Toggle clustering off to view the original point features that make up the clustered elements. When clustering is toggled on, you can tap on a clustered geoelement to view aggregated information and summary statistics for that cluster as well as a list of containing geoelements. When clustering is disabled and you tap 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 to enable or disable clustering on the feature layer.
  4. Use the onSingleTapGesture modifier to listen for tap events on the map view.
  5. Identify tapped features on the map using identify(on:screenPoint:tolerance:returnPopupsOnly:maximumResults:) on the feature layer and pass in the map screen point location.
  6. Get the Popup from the resulting IdentifyLayerResult and use it to construct a PopupView.
  7. Get the AggregateGeoElement from the IdentifyLayerResult and use geoElements to retrieve the contained GeoElement objects.
  8. Use a FloatingPanel to display the popup information from the PopupView and the list containing the GeoElement objects.

Relevant API

  • AggregateGeoElement
  • FeatureLayer
  • FeatureReduction
  • GeoElement
  • IdentifyLayerResult

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 cluster's 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

Graphics in a graphics overlay can also be aggregated into clusters. To do this, set the featureReduction property on the GraphicsOverlay to a new ClusteringFeatureReduction.

Tags

aggregate, bin, cluster, group, merge, normalize, reduce, summarize

Sample Code

DisplayClustersView.swift
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
// 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
//
//   https://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.

import ArcGIS
import ArcGISToolkit
import SwiftUI

struct DisplayClustersView: View {
    /// A map of global power plants.
    @State private var map = {
        let portalItem = PortalItem(
            portal: .arcGISOnline(connection: .anonymous),
            id: PortalItem.ID("8916d50c44c746c1aafae001552bad23")!
        )
        return Map(item: portalItem)
    }()

    /// The power plants feature layer for querying.
    private var layer: FeatureLayer? {
        map.operationalLayers.first as? FeatureLayer
    }

    /// The screen point to perform an identify operation.
    @State private var identifyScreenPoint: CGPoint?

    /// The geoelements in the selected cluster.
    @State private var geoElements: [GeoElement] = []

    /// The popup to be shown as the result of the layer identify operation.
    @State private var popup: Popup?

    /// A Boolean value specifying whether the popup view should be shown or not.
    @State private var showsPopup = false

    /// A Boolean value specifying whether the layer's feature reduction is shown.
    @State private var showsFeatureReduction = true

    /// The error shown in the error alert.
    @State private var error: Error?

    var body: some View {
        MapViewReader { proxy in
            MapView(map: map)
                .onSingleTapGesture { screenPoint, _ in
                    identifyScreenPoint = screenPoint
                }
                .task(id: identifyScreenPoint) {
                    layer?.clearSelection()
                    geoElements.removeAll()

                    guard let identifyScreenPoint,
                          let layer,
                          let identifyResult = try? await proxy.identify(
                            on: layer,
                            screenPoint: identifyScreenPoint,
                            tolerance: 3
                          )
                    else { return }
                    self.popup = identifyResult.popups.first
                    self.showsPopup = self.popup != nil

                    guard let identifyGeoElement = identifyResult.geoElements.first else { return }
                    if let aggregateGeoElement = identifyGeoElement as? AggregateGeoElement {
                        aggregateGeoElement.isSelected = true
                        let geoElements = try? await aggregateGeoElement.geoElements
                        self.geoElements = geoElements ?? []
                    } else if let feature = identifyGeoElement as? Feature {
                        layer.selectFeature(feature)
                    }
                }
                .floatingPanel(
                    selectedDetent: .constant(.half),
                    horizontalAlignment: .leading,
                    isPresented: $showsPopup
                ) { [popup] in
                    PopupView(popup: popup!, isPresented: $showsPopup)
                        .showCloseButton(true)
                        .padding([.top, .horizontal])

                    if !geoElements.isEmpty {
                        List {
                            Section {
                                ForEach(Array(geoElements.enumerated()),
                                        id: \.offset
                                ) { offset, geoElement in
                                    let name = geoElement.attributes["name"] as? String
                                    Text(name ?? "Geoelement: \(offset)")
                                }
                            } header: {
                                Text("Geoelements")
                                    .font(.title3)
                                    .bold()
                                    .foregroundStyle(.primary)
                            }
                        }
                        .listStyle(.inset)
                    }
                }
                .toolbar {
                    ToolbarItem(placement: .bottomBar) {
                        Toggle(
                            showsFeatureReduction ? "Feature Clustering Enabled" : "Feature Clustering Disabled",
                            isOn: $showsFeatureReduction
                        )
                        .onChange(of: showsFeatureReduction) { isEnabled in
                            layer?.featureReduction?.isEnabled = isEnabled
                        }
                    }
                }
                .task {
                    do {
                        try await map.load()
                        await proxy.setViewpointScale(1e7)
                        layer?.featureReduction?.isEnabled = true
                    } catch {
                        self.error = error
                    }
                }
                .errorAlert(presentingError: $error)
        }
    }
}

#Preview {
    NavigationStack {
        DisplayClustersView()
    }
}

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