Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
    <title>Accidents - by time of day</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
    <script type="module" src="https://js.arcgis.com/calcite-components/1.9.2/calcite.esm.js"></script>
    <link rel="stylesheet" type="text/css" href="https://js.arcgis.com/calcite-components/1.9.2/calcite.css"/>
    <link rel="stylesheet" href="https://js.arcgis.com/4.28/esri/themes/light/main.css" />
    <script src="https://js.arcgis.com/4.28/"></script>

    <style>
      html,
      body,
      #viewDiv {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
      }
      
      #infoDiv {
        padding: 10px;
      }
      #rightPanel {
        max-height: 98%;
      }
      calcite-shell-panel {
        --calcite-shell-panel-min-width: 420px;
        --calcite-shell-panel-width: 420px;
        --calcite-shell-panel-max-width: 80%;
      }

      calcite-chip[selected] {
        --calcite-ui-border-1: var(--calcite-ui-brand);
      }

      .canvas {
        margin: 0 auto 1rem
      }

      calcite-chip-group {
        margin: 1rem auto .5rem;
      }
  </style>
   <script>
    require([
      "esri/Map",
      "esri/views/MapView",
      "esri/layers/FeatureLayer",
       "esri/layers/support/AggregateField",
      "esri/layers/support/ExpressionInfo",
      "esri/widgets/Legend",
      "esri/widgets/Expand",
      "esri/core/reactiveUtils"
    ], (
      Map,
      MapView,
      FeatureLayer,
      AggregateField,
      ExpressionInfo,
      Legend,
      Expand,
      reactiveUtils
    ) => (async () => {
      const map = new Map({
        basemap: {
          portalItem: {
            id: "3582b744bba84668b52a16b0b6942544"
          }
        }
      });

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

      const featureReduction = {
        type: "cluster",
        clusterRadius: 12,
        clusterMinSize: 24,
        clusterMaxSize: 32,
        maxScale: 2000000,
        fields: [
          new AggregateField({
            name: "aggregateCount",
            statisticType: "count"
          }),
          new AggregateField({
            name: "total_earlyMorning",
            statisticType: "sum",
            onStatisticExpression: new ExpressionInfo({
              title: "Accidents by hours",
              expression: `
                var d = $feature.TSODate;
                var h = Hour(d);
                return  Number(h <= 6);`
            })
          }),
          new AggregateField({
            name: "total_lateMorning",
            statisticType: "sum",
            onStatisticExpression: new ExpressionInfo({
            title: "Accidents by hours",
            expression: `
               var d = $feature.TSODate;
               var h = Hour(d);
               return  Number(h > 6 && h <= 12);`
            })
          }),
          new AggregateField({
            name: "total_afternoon",
            statisticType: "sum",
            onStatisticExpression: new ExpressionInfo({
              title: "Accidents by hours",
              expression: `
                var d = $feature.TSODate;
                var h = Hour(d);
                return  Number(h > 12 && h <= 17);`
            })
          }),
          new AggregateField({
            name: "total_evening",
            statisticType: "sum",
            onStatisticExpression: new ExpressionInfo({
              title: "Accidents by hours",
              expression: `
                var d = $feature.TSODate;
                var h = Hour(d);
                return  Number(h > 17 && h <= 21);`
              })
          }),
          new AggregateField({
            name: "total_night",
            statisticType: "sum",
            onStatisticExpression: new ExpressionInfo({
              title: "Accidents by hours",
              expression: `
                var d = $feature.TSODate;
                var h = Hour(d);
                return  Number(h > 21);`
            })
          }),
          new AggregateField({
            name: "avg_time",
            statisticType: "avg",
            onStatisticExpression: new ExpressionInfo({
              title: "Accidents by hours",
              returnType: "string",
              expression: `
                var d = $feature.TSODate;
                Hour(d);`
            })
          })
        ],
        clusterRadius: 30,
        clusterMinSize: 6,
        clusterMaxSize: 30,
        popupEnabled: true,
        popupTemplate:  {
          content: [
            {
              type: "text",
              text: "This cluster represents <b>{cluster_count}</b> accidents."
            },
            {
              type: "media",
              mediaInfos: [
                {
                  title: "Fatal accidents",
                  type: "pie-chart",
                  value: {
                    fields: ["total_earlyMorning", "total_lateMorning", "total_afternoon", 'total_evening', "total_night"]
                  }
                }
              ]
            },
            {
              type: "fields"
            }
          ]
        },
        renderer: {
          type: "pie-chart",
          attributes: [{
            field: "total_earlyMorning",
            label: "Early morning - before 6AM",
            color: "purple"
          }, {
            field: "total_lateMorning",
            label: "Late morning - after 6AM and before 12PM",
            color: "yellow"
          }, {
            field: "total_afternoon",
            label: "Afternoon - after 12PM and before 5PM",
            color: "orange"
          }, {
            field: "total_evening",
            label: "Evening - after 5PM and before 9PM",
            color: "blue"
          }, {
            field: "total_night",
            label: "Night - after 9PM until midnight",
            color: "black"
          }],
          defaultSymbol: createSymbol("gray"),
          visualVariables: [
            {
              type: "size",
              field: "aggregateCount",
              legendOptions: {
                title: "Number of crashes"
              },
              stops: [
                { value: 0, size: 1 },
                { value: 300, size: 40 }
              ]
            }
          ]
        }
      };

      const layer = new FeatureLayer({
        title: "Fatal accidents (2021)",
        url: "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/accidents2021/FeatureServer/0",
        outFields: ["*"],
        featureReduction,
        popupTemplate: {
          title: "Crash information",
          fieldInfos: [
            {
              fieldName: "expression/TSO-from-server"
            },
            {
              fieldName: "FATALS",
              label: "Fatalities"
            },
            {
              fieldName: "PERSONS",
              label: "Total number of people in vehicle"
            },
            {
              fieldName: "CITYNAME",
              label: "City"
            },
            {
              fieldName: "PEDS",
              label: "Number of pedestrians"
            }
          ],
          expressionInfos: [
            {
              // timestamp-offset field will display in the time zone from the server
              // with an abbreviated time zone suffix
              expression: `Text($feature.TSODate, "M/D/Y, h:mm A ZZZZ")`,
              name: "TSO-from-server"
            }
          ],
          content: [
            {
              type: "fields"
            }
          ]
        }
      });
                
      function createSymbol (color){
        return {
          type: "simple-marker",
          color: color,
          outline: {
            color: "rgba(153, 31, 23, 0.3)",
            width: 0.3
          }
         };
      }
      map.add(layer);

      let layerView = await view.whenLayerView(layer);
      
      // prepare data for total accidents by time of day chart
      let hourData = [], hourLabels = [];
      let dayDistributionChart; 
      
      reactiveUtils.whenOnce(
        () => !layerView.updating).then(async() => {
          // Accidents by time of day chart
          // run stats query to return total number of accidents by time of day
          // stats results will be grouped by the time of day
          const hourResult = await runQuery("1=1", view.extent, "extract(hour from tsodate)");
          for (let feature of hourResult.features) {
            hourData.push(feature.attributes["count"]);
            hourLabels.push(feature.attributes["EXPR_1"]);
          }

          // create a bar chart showing total number of accidents by time of day
          dayDistributionChart = updateChart("chart-day", hourData, hourLabels);
        });

      view.watch("stationary", async () =>{
        if (!view.stationary) {
          if (dayDistributionChart) {
            let hourResult = await runQuery("1=1", view.extent, "extract(hour from tsodate)");
            hourData = [];
            for (let feature of hourResult.features) {
              hourData.push(feature.attributes["count"]);
            }
            dayDistributionChart.data.datasets[0].data = hourData;
            dayDistributionChart.update();
          }
        }
      });

      // this function is called 3 times when the app loads and generates
      // count stats for accidents 1. by time of day 2. by day of week and 3. by month
      async function runQuery(where, geometry, groupStats) {
        // create a query object that honors the layer settings
        let query = layerView.createQuery();
        query.where = where;
        query.geometry = geometry;
        query.outStatistics = [
          {
            statisticType: "count",
            onStatisticField: "*",
            outStatisticFieldName: "count"
          }
        ];
        query.groupByFieldsForStatistics = [groupStats];
        query.orderByFields = [groupStats];
        let result = await layerView.queryFeatures(query);
        return result;
      }

      // this function is called when the app loads. It creates three charts showing
      // total accidents by time of day, by day of the week and months
      function updateChart(canvas, data, labels) {
        const canvasElement = document.getElementById(canvas);

        const backgroundColors = Array(data.length).fill("#007AC2");
        // Get the canvas element and render the chart in it
        let chart = new Chart(canvasElement.getContext("2d"), {
          type: "bar",
          data: {
            labels: labels,
            datasets: [
              {
                backgroundColor: backgroundColors,
                data: data
              }
            ]
          },
          options: {
            responsive: false,
            legend: {
              display: false
            },
            scales: {
              yAxes: [
                {
                  ticks: {
                    beginAtZero: true,
                    // max: max
                  }
                }
              ]
            },
            tooltips: {
              displayColors: false,
              callbacks: {
                label: (tooltipItem, data) => {
                  const total =
                    data.datasets[tooltipItem.datasetIndex].data[
                      tooltipItem.index
                    ];
                  return (
                    data.labels[tooltipItem.index] +
                    " - Total accidents: " +
                    total
                  );
                }
              }
            }
          }
        });
        return chart;
      }

      // add a legend widget to the view
      const legendExpand = new Expand({
        expandIcon: "legend",
        view: view,
        content: new Legend({
          view,
          layerInfos: [
            {
              layer: layer,
              title: "Fatal accidents by time of day (2021)"
            }
          ]
        })
      });
      view.ui.add(legendExpand, "bottom-left");

      function createSymbol(color) {
        return {
          type: "simple-marker",
          color: color,
          size: "5px",
          outline: null,
          outline: {
            color: "rgba(153, 31, 23, 0.3)",
            width: 0.3
          }
        };
      }
      const infoDiv = document.getElementById("infoDiv");
      view.ui.add(
        new Expand({
            view: view,
            content: infoDiv,
            expandIcon: "list-bullet",
            expanded: false
          }),
        "top-left"
      );
      
       const toggleButton = document.getElementById("showBins");
        toggleButton.onclick = () => {
          layer.featureReduction = layer.featureReduction
            ? null
            : featureReduction;
        };
      
      const legend = new Legend({
        view: view,
        container: "legendDiv"
      });
    })());
  </script>
  </script>
  </head>
  <body>
    <calcite-shell content-behind>
      <div id="viewDiv"></div>
       <div id="infoDiv" class"esri-widget">
        <button id="showBins" class="esri-button">Toggle Clustering</button>
        <div id="legendDiv"></div>
      </div>
      <calcite-shell-panel id="rightPanel" slot="panel-end" display-mode="float">
        <calcite-panel id="statsPanel" heading="Fatal Accidents in USA - 2021" description="Explore accidents data">
          <calcite-block open id="chart-block" heading="Total accidents by time of day - (accidents in the view)">
            <canvas class="canvas" id="chart-day" height="200" width="400"></canvas>
          </calcite-block>
          <calcite-notice slot="footer" open width="full" icon>
            <span slot="title">Note</span>
            <span slot="message">Zoom or pan on the map to see total accidents by time of day within the view</span>
          </calcite-notice>
        </calcite-panel>
      </calcite-shell-panel>
  </calcite-shell>
  </body>
</html>
              
            
!

CSS

              
                
              
            
!

JS

              
                
              
            
!
999px

Console