Point clustering - generate suggested configuration

Explore in the sandboxView live

This sample demonstrates how to generate a default popupTemplate and labels for point clusters enabled in a MapView. To generate a popupTemplate, call the getTemplates() method in the esri/smartMapping/popup/clusters module. Use the getLabelSchemes() method in esri/smartMapping/labels/clusters to generate suggested default labelingInfo for the clusters along with a suggested clusterMinSize.

Configure clustering
157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 178 178 178 178 178 178 178 178 178 178 178 178 178 178 178 178 178 178 178 178 178 178 178 178 178 178 178 178
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta
    name="viewport"
    content="initial-scale=1,maximum-scale=1,user-scalable=no"
  />

<title>Point clustering - generate suggested configuration | Sample | ArcGIS API for JavaScript 4.19</title>

<link rel="stylesheet" href="https://js.arcgis.com/4.19/esri/themes/light/main.css" />
<script src="https://js.arcgis.com/4.19/"></script>

<style>
  html, body, #viewDiv {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
  }
  #infoDiv {
    background: white;
    padding: 10px;
  }
</style>

<script>
  require([
    "esri/WebMap",
    "esri/views/MapView",
    "esri/layers/FeatureLayer",
    "esri/widgets/Legend",
    "esri/widgets/Expand",
    "esri/smartMapping/labels/clusters",
    "esri/smartMapping/popup/clusters"
  ], (Map, MapView, FeatureLayer, Legend, Expand,
    clusterLabelCreator, clusterPopupCreator
  ) => {

    const serviceUrl =
      "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/Places_of_Worship_India/FeatureServer/0";
    const layer = new FeatureLayer({
      url: serviceUrl,
      title: "Places of worship",
      outFields: [ "name", "religion", "denomination" ],
      popupTemplate: {
        title: "{name}",
        content: [
          {
            type: "fields",
            fieldInfos: [
              {
                fieldName: "religion"
              },
              {
                fieldName: "denomination"
              }
            ]
          }
        ]
      }
    });

    const map = new Map({
      basemap: "gray-vector",
      layers: [ layer ]
    });

    const view = new MapView({
      container: "viewDiv",
      map,
      center: [ 80.20127, 22.12355 ],
      zoom: 4
    });

    // Override the default symbol representing the cluster extent
    view.popup.viewModel.selectedClusterBoundaryFeature.symbol = {
      type: "simple-fill",
      style: "solid",
      color: "rgba(50,50,50,0.15)",
      outline: {
        width: 0.5,
        color: "rgba(50,50,50,0.25)"
      }
    }

    const legend = new Legend({
      view,
      container: "legendDiv"
    });

    const infoDiv = document.getElementById("infoDiv");
    view.ui.add(
      new Expand({
        view,
        content: infoDiv,
        expandIconClass: "esri-icon-layer-list",
        expanded: true
      }), "top-right");


    layer.when()
      .then(generateClusterConfig)
      .then((featureReduction) => {

        layer.featureReduction = featureReduction;

        const toggleButton = document.getElementById("toggle-cluster");
        toggleButton.addEventListener("click", toggleClustering);

        // To turn off clustering on a layer, set the
        // featureReduction property to null
        function toggleClustering() {
          if(isWithinScaleThreshold()){
            let fr = layer.featureReduction;
            layer.featureReduction =
              fr && fr.type === "cluster" ? null : featureReduction;
          }
          toggleButton.innerText =
            toggleButton.innerText === "Enable Clustering"
              ? "Disable Clustering"
              : "Enable Clustering";
        }

        view.whenLayerView(layer).then((layerView) => {
          const filterSelect = document.getElementById("filter");
          // filters the layer using a definitionExpression
          // based on a religion selected by the user
          filterSelect.addEventListener("change", (event) => {
            const newValue = event.target.value;

            const whereClause = newValue
              ? `religion = '${newValue}'`
              : null;
            layerView.filter = {
              where: whereClause
            };
            // close popup for former cluster that no longer displays
            view.popup.close();
          });
        });

        view.watch("scale", (scale) => {
          if(toggleButton.innerText === "Disable Clustering"){
            layer.featureReduction = isWithinScaleThreshold() ? featureReduction : null;
          }
        })
      }).catch((error) => {
        console.error(error);
      });

    function isWithinScaleThreshold(){
      return view.scale > 50000;
    }


    async function generateClusterConfig(layer){

      // generates default popupTemplate
      const popupTemplate = await clusterPopupCreator
        .getTemplates({ layer })
        .then(popupTemplateResponse => popupTemplateResponse.primaryTemplate.value);


      // generates default labelingInfo
      const { labelingInfo, clusterMinSize } = await clusterLabelCreator
        .getLabelSchemes({ layer, view })
        .then(labelSchemes => labelSchemes.primaryScheme );


      return {
        type: "cluster",
        popupTemplate,
        labelingInfo,
        clusterMinSize
      };
    }


  });
</script>

</head>

<body>
  <div id="viewDiv"></div>
  <div id="infoDiv" class="esri-widget">
    Filter by religion:
    <select id="filter" class="esri-select">
      <option value="">All</option>
      <option value="Hindu">Hindu</option>
      <option value="Christian">Christian</option>
      <option value="Muslim">Muslim</option>
      <option value="Buddhist">Buddhist</option>
      <option value="Sikh">Sikh</option>
      <option value="Jain">Jain</option>
    </select>
    <div style="padding-top: 10px;">
      <button id="toggle-cluster" class="esri-button">Disable Clustering</button>
    </div>
    <div id="legendDiv"></div>
  </div>
</body>

</html>

Clustering is enabled via the featureReduction property of the FeatureLayer.

Set generated cluster configuration
102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 103 104 105 106 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107 107
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta
    name="viewport"
    content="initial-scale=1,maximum-scale=1,user-scalable=no"
  />

<title>Point clustering - generate suggested configuration | Sample | ArcGIS API for JavaScript 4.19</title>

<link rel="stylesheet" href="https://js.arcgis.com/4.19/esri/themes/light/main.css" />
<script src="https://js.arcgis.com/4.19/"></script>

<style>
  html, body, #viewDiv {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
  }
  #infoDiv {
    background: white;
    padding: 10px;
  }
</style>

<script>
  require([
    "esri/WebMap",
    "esri/views/MapView",
    "esri/layers/FeatureLayer",
    "esri/widgets/Legend",
    "esri/widgets/Expand",
    "esri/smartMapping/labels/clusters",
    "esri/smartMapping/popup/clusters"
  ], (Map, MapView, FeatureLayer, Legend, Expand,
    clusterLabelCreator, clusterPopupCreator
  ) => {

    const serviceUrl =
      "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/Places_of_Worship_India/FeatureServer/0";
    const layer = new FeatureLayer({
      url: serviceUrl,
      title: "Places of worship",
      outFields: [ "name", "religion", "denomination" ],
      popupTemplate: {
        title: "{name}",
        content: [
          {
            type: "fields",
            fieldInfos: [
              {
                fieldName: "religion"
              },
              {
                fieldName: "denomination"
              }
            ]
          }
        ]
      }
    });

    const map = new Map({
      basemap: "gray-vector",
      layers: [ layer ]
    });

    const view = new MapView({
      container: "viewDiv",
      map,
      center: [ 80.20127, 22.12355 ],
      zoom: 4
    });

    // Override the default symbol representing the cluster extent
    view.popup.viewModel.selectedClusterBoundaryFeature.symbol = {
      type: "simple-fill",
      style: "solid",
      color: "rgba(50,50,50,0.15)",
      outline: {
        width: 0.5,
        color: "rgba(50,50,50,0.25)"
      }
    }

    const legend = new Legend({
      view,
      container: "legendDiv"
    });

    const infoDiv = document.getElementById("infoDiv");
    view.ui.add(
      new Expand({
        view,
        content: infoDiv,
        expandIconClass: "esri-icon-layer-list",
        expanded: true
      }), "top-right");


    layer.when()
      .then(generateClusterConfig)
      .then((featureReduction) => {

        layer.featureReduction = featureReduction;

        const toggleButton = document.getElementById("toggle-cluster");
        toggleButton.addEventListener("click", toggleClustering);

        // To turn off clustering on a layer, set the
        // featureReduction property to null
        function toggleClustering() {
          if(isWithinScaleThreshold()){
            let fr = layer.featureReduction;
            layer.featureReduction =
              fr && fr.type === "cluster" ? null : featureReduction;
          }
          toggleButton.innerText =
            toggleButton.innerText === "Enable Clustering"
              ? "Disable Clustering"
              : "Enable Clustering";
        }

        view.whenLayerView(layer).then((layerView) => {
          const filterSelect = document.getElementById("filter");
          // filters the layer using a definitionExpression
          // based on a religion selected by the user
          filterSelect.addEventListener("change", (event) => {
            const newValue = event.target.value;

            const whereClause = newValue
              ? `religion = '${newValue}'`
              : null;
            layerView.filter = {
              where: whereClause
            };
            // close popup for former cluster that no longer displays
            view.popup.close();
          });
        });

        view.watch("scale", (scale) => {
          if(toggleButton.innerText === "Disable Clustering"){
            layer.featureReduction = isWithinScaleThreshold() ? featureReduction : null;
          }
        })
      }).catch((error) => {
        console.error(error);
      });

    function isWithinScaleThreshold(){
      return view.scale > 50000;
    }


    async function generateClusterConfig(layer){

      // generates default popupTemplate
      const popupTemplate = await clusterPopupCreator
        .getTemplates({ layer })
        .then(popupTemplateResponse => popupTemplateResponse.primaryTemplate.value);


      // generates default labelingInfo
      const { labelingInfo, clusterMinSize } = await clusterLabelCreator
        .getLabelSchemes({ layer, view })
        .then(labelSchemes => labelSchemes.primaryScheme );


      return {
        type: "cluster",
        popupTemplate,
        labelingInfo,
        clusterMinSize
      };
    }


  });
</script>

</head>

<body>
  <div id="viewDiv"></div>
  <div id="infoDiv" class="esri-widget">
    Filter by religion:
    <select id="filter" class="esri-select">
      <option value="">All</option>
      <option value="Hindu">Hindu</option>
      <option value="Christian">Christian</option>
      <option value="Muslim">Muslim</option>
      <option value="Buddhist">Buddhist</option>
      <option value="Sikh">Sikh</option>
      <option value="Jain">Jain</option>
    </select>
    <div style="padding-top: 10px;">
      <button id="toggle-cluster" class="esri-button">Disable Clustering</button>
    </div>
    <div id="legendDiv"></div>
  </div>
</body>

</html>

Since a layer's featureReduction property is independent of its renderer, the symbol and popupTemplate of the cluster graphics can be used to summarize features comprising the cluster. See Clustering styles and configurations for more information about the various ways clusters can summarize the points they represent.

The layer in this sample visualizes places of worship with a UniqueValueRenderer. When clustering is enabled, each cluster is assigned the symbol of the most common uniqueValueInfo among the features in the cluster.

Display all pointsDisplay clustered features
clustering-type-disabled clustering-type-enabled

You can reference the predominant value of a cluster in the popupTemplate. For layers with a UniqueValueRenderer, the summary field name follows this format: {cluster_type_fieldName}. In this case, the renderer visualizes unique values in the religion field, so the aggregate field name to reference in the popupTemplate is {cluster_type_religion}.

This sample also demonstrates how you can explore and filter a layer by category with clustering enabled the same way you would on a non-clustered layer. When a filter is applied to the layer view of a clustered layer, the clusters will recompute client-side and only display information complying with the filter.

         
filterSelect.addEventListener("change", (event) => {
  const newValue = event.target.value;
  const whereClause = newValue ? "religion = '" + newValue + "'" : null;
  layerView.filter = {
    where: whereClause
  };
  // close popup for former cluster that no longer displays
  view.popup.close();
});