Display a web map with a point feature layer that has feature reduction enabled to aggregate points into 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
- 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
to enable or disable clustering on the feature layer. - Use the
onSingleTapGesture
modifier to listen for tap events on the map view. - 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. - Get the
Popup
from the resultingIdentifyLayerResult
and use it to construct aPopupView
. - Get the
AggregateGeoElement
from theIdentifyLayerResult
and usegeoElements
to retrieve the containedGeoElement
objects. - Use a
FloatingPanel
to display the popup information from thePopupView
and the list containing theGeoElement
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
// 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()
}
}