Module 10 - Graphics and Client-Side Data

Level 2 · Layers & Data · 🟔 · 3 hours · Prereq: Module 09


What you'll build

A bike-share dashboard fed by a live public JSON API that has nothing to do with Esri. You will convert plain objects into features, load them into a client-side FeatureLayer, and get renderers, popups, labels, filtering and legend entries for free - none of which a GraphicsLayer would give you.


Why this matters

Most real data does not live in a feature service. It lives in your company's REST API, a Postgres table behind an endpoint, a CSV in S3, a spreadsheet, an IoT broker, or a third-party JSON feed.

The naive approach is GraphicsLayer + a loop. It works, and then you need a legend, and a filter, and clustering, and a popup per feature, and you rewrite everything.

The client-side FeatureLayer is the answer, and it is underused. Learning it here saves you a rewrite in Level 4.


Concepts

1. Graphic - the unit of client-side drawing

import Graphic from "@arcgis/core/Graphic.js";

const graphic = new Graphic({
  geometry: { type: "point", longitude: -76.481, latitude: 44.231 },
  symbol:   { type: "simple-marker", color: "#0066ff", size: 10 },
  attributes: { name: "Station 1", bikes: 7 },
  popupTemplate: { title: "{name}", content: "{bikes} bikes available" },
});

Four properties. geometry and attributes are the data; symbol and popupTemplate are presentation, and both are optional - if the graphic lives in a layer with a renderer, the renderer wins.

2. GraphicsLayer vs client-side FeatureLayer

This table is the module.

GraphicsLayer FeatureLayer({ source })
Symbol Per graphic, set individually A renderer - one rule for all
Legend āŒ none āœ… automatic from the renderer
Popups Per graphic One popupTemplate for the layer
Labels āŒ āœ… labelingInfo
Query āŒ loop layer.graphics yourself āœ… queryFeatures, queryFeatureCount, statistics
Filter āŒ āœ… definitionExpression, FeatureFilter, FeatureEffect
Clustering / binning āŒ āœ… featureReduction
Visual variables āŒ āœ…
Time āŒ āœ… timeInfo + TimeSlider
Editing manual āœ… applyEdits
Schema needed no yes - fields, objectIdField, geometryType
Best for Temporary overlays, sketches, highlights Actual data

Rule: if a user should ever be able to filter it, legend it, label it, or click it for attributes, it is a FeatureLayer.

GraphicsLayer is for: a highlight ring, a measurement line being drawn, a crosshair, a temporary buffer preview.

3. Building a client-side FeatureLayer

Four things are required, and omitting any of them produces a confusing failure:

const layer = new FeatureLayer({
  source: graphics,                    // 1. an array of Graphic
  objectIdField: "ObjectID",           // 2. which field is the unique id
  fields: [                            // 3. the schema
    { name: "ObjectID", type: "oid" },
    { name: "name",     type: "string" },
    { name: "bikes",    type: "integer" },
    { name: "updated",  type: "date" },
  ],
  geometryType: "point",               // 4. all features must share this
  spatialReference: { wkid: 4326 },

  renderer: { /* … */ },
  popupTemplate: { /* … */ },
  title: "Bike stations",
});

The four failure modes:

Missing Symptom
objectIdField "Feature layer must have an object id field" or duplicate/lost features
fields Attributes exist but renderers, popups and queries can't see them
geometryType Layer loads, draws nothing
Unique OID values Features overwrite each other; count is wrong

Every feature needs a unique OID value in its attributes. Generate them:

const graphics = records.map((record, index) => new Graphic({
  geometry: { type: "point", longitude: record.lon, latitude: record.lat },
  attributes: { ObjectID: index + 1, ...record },
}));

4. Updating a client-side layer

Two options:

// A. Replace everything - simple, loses selection/highlight state
layer.source = newGraphics;

// B. Incremental - the same API as a real editable service
await layer.applyEdits({
  addFeatures: [g1, g2],
  updateFeatures: [g3],
  deleteFeatures: [{ objectId: 42 }],
});

applyEdits on a client-side layer works exactly like it does on a hosted service. It is worth using even when you own the array, because the code you write is then portable to a real service with no changes. Module 35 builds on this.

5. Geometry from plain data

// Point
{ type: "point", longitude: lon, latitude: lat }
{ type: "point", x, y, spatialReference: { wkid: 3857 } }

// Polyline - array of paths
{ type: "polyline", paths: [[[x1,y1],[x2,y2],[x3,y3]]], spatialReference: { wkid: 4326 } }

// Polygon - array of rings, first vertex repeated last
{ type: "polygon", rings: [[[x1,y1],[x2,y2],[x3,y3],[x1,y1]]], spatialReference: { wkid: 4326 } }

If you're starting from GeoJSON geometry, don't hand-convert:

import { geojsonToArcGIS } from "@arcgis/core/geometry/support/jsonUtils.js";

That helper's exact name varies across releases. The reliable path is GeoJSONLayer (which does the conversion internally), or a tiny converter of your own - GeoJSON's coordinates/Polygon maps to Esri's rings with a winding-order flip. Writing a 20-line converter is a good exercise and removes an unknown from your build.

6. view.graphics - the third option

view.graphics.add(graphic);
view.graphics.removeAll();

Not in map.layers, not in the LayerList, no LayerView, only in this view. Right for a hover highlight that must be instantaneous and must not appear anywhere else. Wrong for everything else.


Build it - the bike-share dashboard

Data source: GBFS (General Bikeshare Feed Specification) - a public, CORS-enabled JSON standard used by hundreds of bike-share systems worldwide. No key needed.

https://gbfs.divvybikes.com/gbfs/en/station_information.json
https://gbfs.divvybikes.com/gbfs/en/station_status.json

(Any GBFS system works - find yours at https://github.com/MobilityData/gbfs/blob/master/systems.csv.)

Step 1 - Fetch and join

// src/gbfs.js

const INFO_URL   = "https://gbfs.divvybikes.com/gbfs/en/station_information.json";
const STATUS_URL = "https://gbfs.divvybikes.com/gbfs/en/station_status.json";

/**
 * Fetch station locations and live availability, and join them on station_id.
 * @returns {Promise<Array<{id,name,lat,lon,capacity,bikesAvailable,docksAvailable,
 *                          pctFull,isRenting,lastReported}>>}
 */
export async function fetchStations() {
  // Two independent requests - run them in parallel (Module 01).
  const [infoRes, statusRes] = await Promise.all([fetch(INFO_URL), fetch(STATUS_URL)]);

  if (!infoRes.ok)   throw new Error(`Station info: HTTP ${infoRes.status}`);
  if (!statusRes.ok) throw new Error(`Station status: HTTP ${statusRes.status}`);

  const info = await infoRes.json();
  const status = await statusRes.json();

  // Index status by id so the join is O(n) instead of O(n²)
  const statusById = new Map(
    status.data.stations.map((s) => [s.station_id, s])
  );

  return info.data.stations
    .map((station) => {
      const live = statusById.get(station.station_id);
      if (!live) return null;                       // a station with no status row

      const capacity = station.capacity ?? 0;
      const bikes = live.num_bikes_available ?? 0;

      return {
        id: station.station_id,
        name: station.name,
        lat: station.lat,
        lon: station.lon,
        capacity,
        bikesAvailable: bikes,
        docksAvailable: live.num_docks_available ?? 0,
        // Guard the divide - a capacity of 0 would give Infinity
        pctFull: capacity > 0 ? Math.round((bikes / capacity) * 100) : 0,
        isRenting: Boolean(live.is_renting),
        lastReported: (live.last_reported ?? 0) * 1000,   // GBFS is seconds; SDK wants ms
      };
    })
    .filter(Boolean)
    // Drop anything without a usable position rather than putting it at Null Island
    .filter((s) => Number.isFinite(s.lat) && Number.isFinite(s.lon));
}

Three details worth noticing:

  1. Promise.all - two independent requests, one round trip's worth of latency.
  2. The Map index - with 1,500 stations, a nested find() is 2.25 million comparisons.
  3. * 1000 - GBFS reports Unix seconds. The SDK's date fields are milliseconds. Get this wrong and every timestamp reads as January 1970. (Module 02 warned you.)

The two .filter() calls are not defensive padding - real feeds contain stations with null coordinates and status rows for decommissioned stations.

Step 2 - Records → Graphics

// src/stationLayer.js
import Graphic from "@arcgis/core/Graphic.js";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer.js";

const FIELDS = [
  { name: "ObjectID",       type: "oid" },
  { name: "stationId",      type: "string",  alias: "Station ID" },
  { name: "name",           type: "string",  alias: "Name" },
  { name: "capacity",       type: "integer", alias: "Capacity" },
  { name: "bikesAvailable", type: "integer", alias: "Bikes available" },
  { name: "docksAvailable", type: "integer", alias: "Docks available" },
  { name: "pctFull",        type: "integer", alias: "Percent full" },
  { name: "isRenting",      type: "integer", alias: "Renting" },
  { name: "lastReported",   type: "date",    alias: "Last reported" },
];

function toGraphic(station, index) {
  return new Graphic({
    geometry: {
      type: "point",
      longitude: station.lon,
      latitude: station.lat,
      spatialReference: { wkid: 4326 },
    },
    attributes: {
      ObjectID: index + 1,
      stationId: station.id,
      name: station.name,
      capacity: station.capacity,
      bikesAvailable: station.bikesAvailable,
      docksAvailable: station.docksAvailable,
      pctFull: station.pctFull,
      // No boolean field type in a feature service - store 0/1
      isRenting: station.isRenting ? 1 : 0,
      lastReported: station.lastReported,
    },
  });
}

export function createStationLayer(stations) {
  return new FeatureLayer({
    source: stations.map(toGraphic),
    objectIdField: "ObjectID",
    fields: FIELDS,
    geometryType: "point",
    spatialReference: { wkid: 4326 },
    title: "Bike stations",

    outFields: ["*"],   // client-side: everything is already here, no cost

    renderer: {
      type: "class-breaks",
      field: "pctFull",
      defaultSymbol: {
        type: "simple-marker", color: "#9ca3af", size: 8,
        outline: { color: "white", width: 1 },
      },
      defaultLabel: "No data",
      classBreakInfos: [
        { minValue: 0,  maxValue: 10,  label: "Empty (0-10%)",
          symbol: marker("#d73027") },
        { minValue: 10, maxValue: 40,  label: "Low (10-40%)",
          symbol: marker("#fc8d59") },
        { minValue: 40, maxValue: 70,  label: "Balanced (40-70%)",
          symbol: marker("#91cf60") },
        { minValue: 70, maxValue: 100, label: "Full (70-100%)",
          symbol: marker("#1a9850") },
      ],
    },

    popupTemplate: {
      title: "{name}",
      content: [
        {
          type: "fields",
          fieldInfos: [
            { fieldName: "bikesAvailable", label: "Bikes available" },
            { fieldName: "docksAvailable", label: "Docks available" },
            { fieldName: "capacity",       label: "Capacity" },
            { fieldName: "pctFull",        label: "Percent full",
              format: { places: 0, digitSeparator: false } },
            { fieldName: "lastReported",   label: "Last reported",
              format: { dateFormat: "short-date-short-time" } },
          ],
        },
      ],
    },
  });
}

const marker = (color) => ({
  type: "simple-marker",
  color,
  size: 9,
  outline: { color: "white", width: 1 },
});

Stop and appreciate what those 60 lines bought you. A legend that generates itself, popups with formatted dates, a colour scheme driven by data, and - for free, in the next step - filtering, clustering and queries. A GraphicsLayer version would be about the same length and would have none of it.

Step 3 - Live refresh with applyEdits

// src/main.js
import { fetchStations } from "./gbfs.js";
import { createStationLayer } from "./stationLayer.js";

let layer = null;
let refreshTimer = null;

async function initialise(view) {
  const stations = await fetchStations();
  layer = createStationLayer(stations);
  view.map.add(layer);

  await view.goTo(layer.fullExtent.expand(1.1)).catch(() => {});

  startAutoRefresh(60_000);
}

function startAutoRefresh(intervalMs) {
  clearInterval(refreshTimer);
  refreshTimer = setInterval(refresh, intervalMs);
}

async function refresh() {
  try {
    const stations = await fetchStations();

    // Read what's currently in the layer so we can compute a diff
    const { features: existing } = await layer.queryFeatures({
      where: "1=1",
      outFields: ["ObjectID", "stationId"],
      returnGeometry: false,
    });

    const oidByStationId = new Map(
      existing.map((f) => [f.attributes.stationId, f.attributes.ObjectID])
    );

    const updates = stations
      .filter((s) => oidByStationId.has(s.id))
      .map((s) => ({
        attributes: {
          ObjectID: oidByStationId.get(s.id),
          bikesAvailable: s.bikesAvailable,
          docksAvailable: s.docksAvailable,
          pctFull: s.pctFull,
          isRenting: s.isRenting ? 1 : 0,
          lastReported: s.lastReported,
        },
      }));

    await layer.applyEdits({ updateFeatures: updates });
    setStatus(`Updated ${updates.length} stations at ${new Date().toLocaleTimeString()}`);
  } catch (error) {
    setStatus(`Refresh failed: ${error.message}`, "error");
  }
}

Why applyEdits rather than layer.source = newGraphics:

  • Selection and highlight survive
  • The popup stays open on the station the user is reading
  • The view redraws only what changed instead of re-tessellating everything
  • The code is identical to what you'd write against a hosted service

Only the changed attributes are sent - geometry is omitted because stations don't move. Including unchanged geometry would force a re-tessellation for nothing.

Step 4 - Client-side query and statistics

async function summarise() {
  const stats = await layer.queryFeatures({
    where: "isRenting = 1",
    outStatistics: [
      { statisticType: "count", onStatisticField: "ObjectID",       outStatisticFieldName: "stations" },
      { statisticType: "sum",   onStatisticField: "bikesAvailable", outStatisticFieldName: "bikes" },
      { statisticType: "sum",   onStatisticField: "capacity",       outStatisticFieldName: "docks" },
      { statisticType: "avg",   onStatisticField: "pctFull",        outStatisticFieldName: "avgFull" },
    ],
  });

  const { stations, bikes, docks, avgFull } = stats.features[0].attributes;

  document.getElementById("summary").innerHTML = `
    <strong>${stations}</strong> active stations Ā·
    <strong>${bikes}</strong> bikes Ā·
    <strong>${docks}</strong> docks Ā·
    avg <strong>${Math.round(avgFull)}%</strong> full
  `;
}

async function emptyStations() {
  const { features } = await layer.queryFeatures({
    where: "bikesAvailable = 0 AND isRenting = 1",
    outFields: ["name", "capacity"],
    orderByFields: ["capacity DESC"],
    returnGeometry: false,
  });
  return features.map((f) => f.attributes);
}

outStatistics works on a client-side layer. The SDK runs the aggregation over the in-memory features. Same API as a hosted service - write it once, works either way.

Step 5 - Filter without touching the data

const view = mapEl.view;
const layerView = await view.whenLayerView(layer);

document.getElementById("onlyEmpty").addEventListener("change", (event) => {
  layerView.filter = event.target.checked
    ? { where: "bikesAvailable = 0" }
    : null;
});

// Or: keep them visible but push them back visually
document.getElementById("dimFull").addEventListener("change", (event) => {
  layerView.effect = event.target.checked
    ? {
        filter: { where: "pctFull < 90" },
        excludedEffect: "grayscale(100%) opacity(25%)",
      }
    : null;
});

filter hides; effect de-emphasises while keeping context. The second is almost always the better user experience, and it costs one extra line. Module 21 covers both properly.

Step 6 - Clustering for the small-scale view

layer.featureReduction = {
  type: "cluster",
  clusterRadius: "70px",
  clusterMinSize: 18,
  clusterMaxSize: 44,
  popupTemplate: {
    title: "{cluster_count} stations",
    content: "Average {cluster_avg_pctFull}% full",
    fieldInfos: [{
      fieldName: "cluster_avg_pctFull",
      format: { places: 0 },
    }],
  },
  labelingInfo: [{
    deconflictionStrategy: "none",
    labelExpressionInfo: { expression: "Text($feature.cluster_count, '#,###')" },
    symbol: { type: "text", color: "white", font: { weight: "bold", size: 11 } },
    labelPlacement: "center-center",
  }],
};

cluster_count and cluster_avg_<field> are generated automatically for numeric fields. You get aggregate popups with no work.

Zoom out and 1,500 markers become 30 readable clusters. This is only possible because it is a FeatureLayer. A GraphicsLayer cannot cluster at all.


How it works

Where a client-side layer's data actually lives

The source array is copied into the layer's in-memory feature store, and after that layer.source is a Collection, not your original array. Mutating your array does nothing.

Queries, statistics, filters and clustering all run against that store using the same code paths as a remote layer - the only difference is that the "request" is answered locally instead of over HTTP.

This is why the API is identical. Esri implemented one query engine and gave it two back-ends.

Why objectIdField is mandatory

Every operation that identifies a specific feature - highlight, popup, applyEdits, selection, queryFeatures by id - needs a stable key. Without one there is no way to say "update that one."

The SDK will generate OIDs if you use GeoJSONLayer (which is a client-side layer under the hood), but for FeatureLayer({ source }) you supply them.

Why fields is mandatory

The renderer, the popup, labels and the query parser all need types:

  • A class-breaks renderer needs to know the field is numeric
  • A date format needs to know the field is a date
  • where: "name = 'X'" needs to know name is a string so it quotes correctly
  • The legend needs an alias to display

Attributes alone carry values, not types. Types come from fields.

Boolean fields don't exist

Feature services have no boolean field type. Use small-integer with 0/1, and if the service is real, add a coded-value domain (0 = No, 1 = Yes). Your SQL becomes isRenting = 1, not isRenting = true - the latter is a SQL error, though the message won't say so clearly.


Common mistakes

Using GraphicsLayer for data. Then discovering you need a legend, a filter, or clustering.

Forgetting the OID, or reusing values. Features silently collapse into each other.

Not declaring fields. Renderers and popups can't see the attributes.

Mixing geometry types in one source. geometryType is a single value for the layer. Points and polygons need two layers.

Mutating the array you passed as source. It was copied. Use applyEdits or reassign layer.source.

Rebuilding the whole layer on every refresh. Kills selection and open popups, and re-tessellates everything. Use applyEdits.

Unix seconds where the SDK wants milliseconds. Everything reads 1970.

isRenting = true in a where clause. Store 0/1 and compare numerically.


Exercises

Exercise 10.1 - Add a second geometry type

Add polylines showing the movement of stations that changed by more than 5 bikes since the last refresh: a line from the station to a point offset by the delta.

You will need a second layer, because geometryType is per-layer. Note in a comment why.

Exercise 10.2 - GeoJSON round trip

Write two functions:

  • graphicsToGeoJson(graphics) → a valid RFC 7946 FeatureCollection
  • geoJsonToGraphics(featureCollection) → an array of Graphic

Handle points, lines and polygons. Watch the winding order on polygons (Module 02). Verify by exporting, re-importing, and confirming the map looks identical.

Exercise 10.3 - Your own API

Replace GBFS with something you care about: your company's API, a public transit feed, an air quality API, a Google Sheet published as CSV.

Requirements:

  • Handle a request failure without blanking the map
  • Handle records with missing coordinates
  • Show a "last updated" timestamp
  • Declare every field with the right type

Exercise 10.4 - The comparison, measured

Build the same 1,500-station map twice - once with GraphicsLayer, once with client-side FeatureLayer - and produce a table:

GraphicsLayer FeatureLayer
Lines of code
Time to first render
Legend
Filter by availability
Cluster at zoom 10
Query "how many empty?"

The point is not that FeatureLayer wins. It is knowing exactly what it wins and by how much, so you can defend the choice.


Checkpoint

  1. Name three things a client-side FeatureLayer gives you that a GraphicsLayer doesn't.
  2. What four properties are required to construct a FeatureLayer from source?
  3. Why does applyEdits beat layer.source = newGraphics for a live refresh?
  4. Your date field shows January 1970. What happened?
  5. How do you store a boolean in a feature layer?
  6. When is GraphicsLayer actually the right choice?
  7. Why can't one FeatureLayer hold both points and polygons?
  1. Any three of: a legend from the renderer, queryFeatures/outStatistics, FeatureFilter and FeatureEffect, clustering/binning, labels, visual variables, time support, applyEdits.
  2. source, objectIdField, fields, geometryType (plus unique OID values in every feature's attributes, and normally spatialReference).
  3. It preserves selection, highlight and open popups, redraws only what changed, and the code is identical to what a hosted service needs.
  4. You passed Unix seconds where the SDK expects milliseconds. Multiply by 1000.
  5. There's no boolean field type. Use small-integer with 0/1, ideally with a coded-value domain, and compare with = 1 in SQL.
  6. Transient, view-specific overlays: hover highlights, a line being drawn, a crosshair, a preview buffer - anything that shouldn't appear in a legend or be filterable.
  7. geometryType is a single layer-level property. The renderer, the tessellation path and the underlying schema all assume one type.

Further reading


Next: Module 11 - Popups That Don't Embarrass You