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 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 callsetEnabled(bool enabled)to enable or disable clustering on the feature layer. - When the user clicks on the map, call
identifyFeatureLayerAsyncon the feature layer and pass in the map click location. - Get the
Popupfrom the resultingIdentifyLayerResultand use it to construct aPopupManager. - Get the feature’s
customHtmlDescriptionfrom the createdPopupManagerand use it to set the MapView’sCalloutDatadetail and display the callout.
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 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.
Tags
aggregate, bin, cluster, group, merge, normalize, reduce, summarize
Sample Code
// [WriteFile Name=DisplayClusters, Category=DisplayInformation]// [Legal]// 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.// [Legal]
#ifdef PCH_BUILD#include "pch.hpp"#endif // PCH_BUILD
// sample headers#include "DisplayClusters.h"
// ArcGIS Maps SDK headers#include "AggregateGeoElement.h"#include "CalloutData.h"#include "Error.h"#include "FeatureLayer.h"#include "FeatureReduction.h"#include "FeatureTable.h"#include "GeoElement.h"#include "IdentifyLayerResult.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "Point.h"#include "Popup.h"#include "PopupManager.h"#include "PortalItem.h"
// Qt headers#include <QFuture>
using namespace Esri::ArcGISRuntime;
DisplayClusters::DisplayClusters(QObject* parent /* = nullptr */): QObject(parent), m_map(new Map(new PortalItem("8916d50c44c746c1aafae001552bad23", this), this)){ connect(m_map, &Map::doneLoading, this, [this](const Error& e) { if (!e.isEmpty()) { qWarning() << e.message() << e.additionalMessage(); return; }
// Get the power plants feature layer for querying m_powerPlantsLayer = static_cast<FeatureLayer*>(m_map->operationalLayers()->first()); m_taskRunning = false; emit taskRunningChanged(); });}
DisplayClusters::~DisplayClusters() = default;
void DisplayClusters::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<DisplayClusters>("Esri.Samples", 1, 0, "DisplayClustersSample");}
MapQuickView* DisplayClusters::mapView() const{ return m_mapView;}
// Set the view (created in QML)void DisplayClusters::setMapView(MapQuickView* mapView){ if (!mapView || mapView == m_mapView) return;
m_mapView = mapView; m_mapView->setMap(m_map);
connect(m_mapView, &MapQuickView::mouseClicked, this, &DisplayClusters::onMouseClicked);
emit mapViewChanged();}
void DisplayClusters::onMouseClicked(const QMouseEvent &mouseClick){ if (m_taskRunning) return;
m_taskRunning = true; emit taskRunningChanged();
m_mapView->calloutData()->setVisible(false);
// clear cluster selection if (m_aggregateGeoElement) m_aggregateGeoElement->setSelected(false);
// Clean up any children objects associated with this parent m_resultParent.reset(new QObject(this)); m_aggregateGeoElement = nullptr;
m_mapView->identifyLayerAsync(m_powerPlantsLayer, mouseClick.position(), 3, false, m_resultParent.get()) .then(this, [this](IdentifyLayerResult* identifyResult) { m_taskRunning = false; emit taskRunningChanged();
// Invalid identify result if (!identifyResult) return;
if (!identifyResult->error().isEmpty()) { qDebug() << "Identify error occurred:" << identifyResult->error().message() << identifyResult->error().additionalMessage(); return; }
if (identifyResult->popups().isEmpty()) return;
Popup* popup = identifyResult->popups().constFirst();
// if the identified object is a cluster, select it m_aggregateGeoElement = dynamic_cast<AggregateGeoElement*>(popup->geoElement()); if (m_aggregateGeoElement) m_aggregateGeoElement->setSelected(true);
// Create a PopupManager with the IdentifyLayerResult's parent so it will get cleaned up as well. PopupManager* popupManager = new PopupManager(popup, identifyResult->parent());
// Use the custom HTML description in the PopupManager to popuplate a Callout and display it. m_calloutText = popupManager->customHtmlDescription(); m_mapView->calloutData()->setLocation(Point(popup->geoElement()->geometry())); m_mapView->calloutData()->setVisible(true);
emit calloutTextChanged(); });}
void DisplayClusters::toggleClustering(){ if (m_map->loadStatus() != LoadStatus::Loaded) return;
if (!m_powerPlantsLayer) { m_powerPlantsLayer = static_cast<FeatureLayer*>(m_map->operationalLayers()->first());
// Check if the cast was successful if (!m_powerPlantsLayer) return; }
m_powerPlantsLayer->featureReduction()->setEnabled(!m_powerPlantsLayer->featureReduction()->isEnabled());
m_mapView->calloutData()->setVisible(false);}
QString DisplayClusters::calloutText() const{ return m_calloutText;}
bool DisplayClusters::taskRunning() const{ return m_taskRunning;}// [WriteFile Name=DisplayClusters, Category=DisplayInformation]// [Legal]// 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.// [Legal]
#ifndef DISPLAYCLUSTERS_H#define DISPLAYCLUSTERS_H
// Qt headers#include <QMouseEvent>#include <QObject>
namespace Esri::ArcGISRuntime{class AggregateGeoElement;class FeatureLayer;class Map;class MapQuickView;}
Q_MOC_INCLUDE("MapQuickView.h");
class DisplayClusters : public QObject{ Q_OBJECT
Q_PROPERTY(Esri::ArcGISRuntime::MapQuickView* mapView READ mapView WRITE setMapView NOTIFY mapViewChanged) Q_PROPERTY(bool taskRunning READ taskRunning NOTIFY taskRunningChanged) Q_PROPERTY(QString calloutText READ calloutText NOTIFY calloutTextChanged)
public: explicit DisplayClusters(QObject* parent = nullptr); ~DisplayClusters() override;
Q_INVOKABLE void toggleClustering();
static void init();
signals: void mapViewChanged(); void taskRunningChanged(); void calloutTextChanged();
private: Esri::ArcGISRuntime::MapQuickView* mapView() const; void setMapView(Esri::ArcGISRuntime::MapQuickView* mapView); QString calloutText() const;
void onMouseClicked(const QMouseEvent& mouseEvent);
Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr;
Esri::ArcGISRuntime::FeatureLayer* m_powerPlantsLayer = nullptr;
bool taskRunning() const; bool m_taskRunning = true; QString m_calloutText = "";
QScopedPointer<QObject> m_resultParent; Esri::ArcGISRuntime::AggregateGeoElement* m_aggregateGeoElement = nullptr;};
#endif // DISPLAYCLUSTERS_H// [WriteFile Name=DisplayClusters, Category=DisplayInformation]// [Legal]// 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.// [Legal]
import QtQuickimport QtQuick.Controlsimport Esri.Samplesimport Esri.ArcGISRuntime.Toolkit
Item {
// add a mapView component MapView { id: view anchors.fill: parent
Component.onCompleted: { // Set and keep the focus on MapView to enable keyboard navigation forceActiveFocus(); } }
// Declare the C++ instance which creates the map etc. and supply the view DisplayClustersSample { id: model mapView: view }
Button { id: clusterToggleButton width: 250 height: 50 text: qsTr("Toggle feature clustering") anchors { top: parent.top right: parent.right margins: 15 } enabled: !model.taskRunning onClicked: model.toggleClustering() }
Callout { id: callout calloutData: view.calloutData implicitWidth: 150 implicitHeight: contentText.implicitHeight + (contentText.implicitHeight * .05) contentItem: Label { id: contentText text: model.calloutText wrapMode: Text.WordWrap textFormat: Text.RichText horizontalAlignment: Qt.AlignHCenter verticalAlignment: Qt.AlignVCenter } }
BusyIndicator { anchors.centerIn: parent running: model.taskRunning }}//"DisplayClusters - C++"// [Legal]// Copyright 2020 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.// [Legal]
// sample headers#include "DisplayClusters.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QDir>#include <QGuiApplication>#include <QQmlApplicationEngine>
// Other headers#include "Esri/ArcGISRuntime/Toolkit/register.h"
// Platform specific headers#ifdef Q_OS_WIN#include <Windows.h>#endif
int main(int argc, char *argv[]){ Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setUseLegacyAuthentication(false); QGuiApplication app(argc, argv); app.setApplicationName(QString("DisplayClusters"));
// Use of ArcGIS location services, such as basemap styles, geocoding, and routing services, // requires an access token. For more information see // https://links.esri.com/arcgis-runtime-security-auth.
// The following methods grant an access token:
// 1. User authentication: Grants a temporary access token associated with a user's ArcGIS account. // To generate a token, a user logs in to the app with an ArcGIS account that is part of an // organization in ArcGIS Online or ArcGIS Enterprise.
// 2. API key authentication: Get a long-lived access token that gives your application access to // ArcGIS location services. Go to the tutorial at https://links.esri.com/create-an-api-key. // Copy the API Key access token.
const QString accessToken = QString("");
if (accessToken.isEmpty()) { qWarning() << "Use of ArcGIS location services, such as the basemap styles service, requires" << "you to authenticate with an ArcGIS account or set the API Key property."; } else { Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setApiKey(accessToken); }
// Initialize the sample DisplayClusters::init();
// Initialize application view QQmlApplicationEngine engine; // Add the import Path engine.addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml"));
#ifdef ARCGIS_RUNTIME_IMPORT_PATH_2 engine.addImportPath(ARCGIS_RUNTIME_IMPORT_PATH_2);#endif
Esri::ArcGISRuntime::Toolkit::registerComponents(engine);
// Set the source engine.load(QUrl("qrc:/Samples/DisplayInformation/DisplayClusters/main.qml"));
return app.exec();}// 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.
import QtQuick.Controlsimport Esri.Samples
ApplicationWindow { visible: true width: 800 height: 600
DisplayClusters { anchors.fill: parent }}