Module 08 - FeatureLayer: the Workhorse
Level 2 Β· Layers & Data Β· π’π‘ Β· 4 hours Β· Prereq: Module 07
What you'll build
A layer inspector: point it at any feature service URL and it reports the geometry type, fields with their types and domains, record count, extent, capabilities and renderer - then adds it to the map with sensible defaults and zooms to its data.
You will use this tool for the rest of the course.
Why this matters
FeatureLayer is 80% of the layers you will ever create. Every subsequent module - symbology,
popups, filtering, querying, editing - operates on it. The properties you learn here are the
control surface for all of that.
It is also where the async lifecycle stops being theoretical. This is the module where "why is
layer.fields null" happens to you personally.
Concepts
1. Four ways to construct one
// 1. From a feature service URL - the most common
new FeatureLayer({
url: "https://services.arcgis.com/.../FeatureServer/0",
});
// 2. From a portal item - carries the item's saved symbology, popup and fields
new FeatureLayer({
portalItem: { id: "f9b908f1c9f4e0a" },
layerId: 0, // required if the item has several layers
});
// 3. From client-side graphics - a "feature collection"
new FeatureLayer({
source: [graphic1, graphic2],
objectIdField: "ObjectID",
fields: [
{ name: "ObjectID", type: "oid" },
{ name: "name", type: "string" },
{ name: "value", type: "double" },
],
geometryType: "point",
spatialReference: { wkid: 4326 },
});
// 4. From a WebMap - you don't construct it, you find it
const layer = webmap.layers.find((l) => l.title === "Parcels");
Note the /0 at the end of a service URL. A FeatureServer is a service; the number is
the layer within it. Omit it and you get an error telling you to specify a layer.
Option 3 is important and underused. A client-side FeatureLayer gets you renderers, popups, labels, queries, filtering and legend entries for data you fetched from a non-Esri API. Module 10 covers it properly.
2. The properties that matter
const layer = new FeatureLayer({
url: SERVICE_URL,
// ββ What data comes back ββ
outFields: ["NAME", "POPULATION"], // attributes to download. ["*"] = everything
definitionExpression: "POPULATION > 50000", // server-side SQL WHERE
returnZ: false, // skip Z values if you don't need them
// ββ How it draws ββ
renderer: { /* Module 14 */ },
labelingInfo: [ /* Module 12 */ ],
opacity: 0.85,
minScale: 500000, // hidden when zoomed out past this
maxScale: 0, // 0 = no limit when zoomed in
elevationInfo: { mode: "on-the-ground" }, // 3D only
// ββ Metadata / UI ββ
title: "US Major Cities", // legend + LayerList label
id: "cities", // your own handle: map.findLayerById("cities")
visible: true,
listMode: "show", // "show" | "hide" | "hide-children"
legendEnabled: true,
popupEnabled: true,
popupTemplate: { /* Module 11 */ },
});
outFields is the one people get wrong.
- Default is
["*"]in most paths - every field for every feature - A 40-field service Γ 50,000 features is megabytes of attributes you never read
- But: your popup, renderer, labels and any client-side query can only see downloaded fields
Symptom of getting it wrong: {FIELD} renders literally in a popup, or a client-side query
returns undefined for a field you know exists. The fix is adding it to outFields.
Rule: list exactly what you use. Use ["*"] only while exploring.
3. The load lifecycle, concretely
const layer = new FeatureLayer({ url: SERVICE_URL });
console.log(layer.loadStatus); // "not-loaded"
console.log(layer.fields); // null
console.log(layer.geometryType); // null
console.log(layer.fullExtent); // null
await layer.load(); // β one request to the service's metadata endpoint
console.log(layer.loadStatus); // "loaded"
console.log(layer.fields.length); // 12
console.log(layer.geometryType); // "point"
console.log(layer.objectIdField); // "OBJECTID" (or FID, or esri_oidβ¦)
console.log(layer.fullExtent); // Extent of all the data
console.log(layer.capabilities); // what the service allows
load() is idempotent and safe to call repeatedly - it returns the same Promise. Adding the
layer to a map loads it implicitly, which is why omitting load() "sometimes works."
Don't rely on that race.
Error handling:
try {
await layer.load();
} catch (error) {
// Common: 400 (bad URL), 403 (no access / bad token), 499 (token required), CORS
console.error(`Layer failed: ${error.name} - ${error.message}`);
}
4. capabilities - what the service will let you do
await layer.load();
const c = layer.capabilities;
c.operations.supportsQuery // can you query it?
c.operations.supportsAdd // can you create features?
c.operations.supportsUpdate
c.operations.supportsDelete
c.operations.supportsEditing
c.query.supportsStatistics // server-side aggregation? (Module 26)
c.query.supportsDistinct
c.query.supportsPagination // can you page past maxRecordCount?
c.query.supportsOrderBy
c.query.maxRecordCount // usually 1000 or 2000
c.data.supportsAttachment // photos on features? (Module 35)
Check capabilities before building UI. A "Delete" button on a read-only service is a bug report waiting to happen. Module 35 makes this a hard requirement.
5. Fields, types and domains
await layer.load();
for (const field of layer.fields) {
console.log(field.name, field.type, field.alias, field.length, field.nullable);
}
field.type |
JS value | Notes |
|---|---|---|
oid |
number | The primary key. layer.objectIdField names it |
global-id |
string | A GUID. Stable across republishing |
string |
string | Has length - exceeding it fails an edit |
small-integer / integer / big-integer |
number | |
single / double |
number | |
date |
number - epoch ms UTC | Not a string, not a Date |
date-only / time-only / timestamp-offset |
Newer types, less common | |
blob / raster / geometry / xml |
Rare in web contexts |
field.alias is the human-readable name. Use it in UI, not field.name. A service with
POP2020 will usually have alias "Population (2020)".
Coded value domains:
const field = layer.fields.find((f) => f.name === "STATUS");
if (field.domain?.type === "coded-value") {
for (const cv of field.domain.codedValues) {
console.log(cv.code, "β", cv.name); // 1 β "Active"
}
}
Popups showing raw codes instead of labels means an unresolved domain. Arcade's DomainName()
(Module 17) fixes it declaratively.
6. Layer visibility by scale
layer.minScale = 250000; // hidden when zoomed OUT beyond 1:250,000
layer.maxScale = 2500; // hidden when zoomed IN beyond 1:2,500
Counter-intuitive because scale denominators get larger as you zoom out. minScale is the
zoomed-out limit and the bigger number. Everyone gets this wrong once.
Why it matters beyond aesthetics: a hidden layer issues no queries and does no tessellation. Scale-limiting a detailed layer is one of the cheapest performance wins available (Module 40).
7. refresh() and refreshInterval
layer.refresh(); // re-fetch now
layer.refreshInterval = 0.5; // minutes - auto-refresh every 30 s
Useful for slowly-changing operational data. For real-time, use a StreamLayer (Module 36) -
polling a feature service every second is abusive to the server and to your quota.
8. Where the data actually comes from
A FeatureLayer does not download everything. The LayerView requests features for the current
extent, at the current scale, honouring definitionExpression and outFields. Pan and it asks
for more. Zoom out past maxRecordCount and the server truncates - which is why a layer can
appear to "lose" features when you zoom out.
Two featureReduction options change this (2D):
layer.featureReduction = { type: "cluster", clusterRadius: "60px" }; // Module 14
layer.featureReduction = { type: "binning", fixedBinLevel: 6 };
Both let a huge point layer stay legible and fast at small scales.
Build it - the layer inspector
Step 1 - Markup
<div class="layout">
<aside id="sidebar">
<h1>Layer Inspector</h1>
<label for="url">Feature service URL</label>
<input id="url" type="url" spellcheck="false"
value="https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_Major_Cities/FeatureServer/0" />
<button id="load" type="button">Load</button>
<div id="status" class="status"></div>
<div id="report"></div>
</aside>
<arcgis-map id="map" basemap="arcgis/light-gray" center="-98,39" zoom="4">
<arcgis-zoom position="top-left"></arcgis-zoom>
<arcgis-legend position="bottom-left"></arcgis-legend>
</arcgis-map>
</div>
Step 2 - Load and report
// src/inspector.js
import FeatureLayer from "@arcgis/core/layers/FeatureLayer.js";
/**
* Load a feature service and return a plain-object description of it.
* Throws with a readable message if the service can't be loaded.
*/
export async function inspectLayer(url) {
const layer = new FeatureLayer({ url, outFields: ["*"] });
try {
await layer.load();
} catch (error) {
throw new Error(describeLoadError(error, url));
}
// Count is a separate request - the metadata doesn't include it.
let count = null;
try {
count = await layer.queryFeatureCount();
} catch {
// Some services disallow count queries; not fatal.
}
return {
layer,
title: layer.title,
geometryType: layer.geometryType,
objectIdField: layer.objectIdField,
displayField: layer.displayField,
spatialReference: layer.spatialReference?.wkid,
count,
extent: layer.fullExtent,
fields: layer.fields.map((f) => ({
name: f.name,
alias: f.alias,
type: f.type,
nullable: f.nullable,
length: f.length,
domain: f.domain?.type === "coded-value"
? f.domain.codedValues.map((cv) => `${cv.code}=${cv.name}`).join(", ")
: null,
})),
capabilities: {
query: layer.capabilities?.operations?.supportsQuery ?? false,
add: layer.capabilities?.operations?.supportsAdd ?? false,
update: layer.capabilities?.operations?.supportsUpdate ?? false,
delete: layer.capabilities?.operations?.supportsDelete ?? false,
statistics: layer.capabilities?.query?.supportsStatistics ?? false,
pagination: layer.capabilities?.query?.supportsPagination ?? false,
attachments: layer.capabilities?.data?.supportsAttachment ?? false,
maxRecordCount: layer.capabilities?.query?.maxRecordCount ?? null,
},
rendererType: layer.renderer?.type ?? "none",
};
}
function describeLoadError(error, url) {
const message = error?.message ?? String(error);
if (message.includes("403")) {
return `403 - the service exists but you're not authorised. Check your API key's ` +
`privileges, or sign in if the item is private.\n${url}`;
}
if (message.includes("499") || message.toLowerCase().includes("token")) {
return `Token required - this is a secured service. See Module 39.\n${url}`;
}
if (message.includes("400")) {
return `400 - the URL is probably wrong. A layer URL ends with a layer index, ` +
`e.g. .../FeatureServer/0\n${url}`;
}
if (message.toLowerCase().includes("cors")) {
return `CORS blocked - the server doesn't allow browser requests from this origin.\n${url}`;
}
return `${error?.name ?? "Error"}: ${message}\n${url}`;
}
The error mapping is the valuable part. The SDK's raw errors are accurate but terse. Translating the four common failures into "here's what to do" is the difference between a tool you use and a tool you abandon.
Step 3 - Render the report
// src/main.js
import { inspectLayer } from "./inspector.js";
const urlInput = document.getElementById("url");
const statusEl = document.getElementById("status");
const reportEl = document.getElementById("report");
const mapEl = document.getElementById("map");
let currentLayer = null;
document.getElementById("load").addEventListener("click", async () => {
const url = urlInput.value.trim();
if (!url) return;
statusEl.textContent = "Loadingβ¦";
statusEl.className = "status status--busy";
reportEl.innerHTML = "";
try {
const info = await inspectLayer(url);
// Swap the layer on the map
const view = mapEl.view;
if (currentLayer) view.map.remove(currentLayer);
currentLayer = info.layer;
view.map.add(currentLayer);
// Zoom to the data, not to wherever we were
if (info.extent) {
await view.goTo(info.extent.expand(1.1)).catch(() => {});
}
statusEl.textContent = `Loaded: ${info.title}`;
statusEl.className = "status status--ok";
reportEl.innerHTML = renderReport(info);
} catch (error) {
statusEl.textContent = error.message;
statusEl.className = "status status--error";
}
});
function renderReport(info) {
const yes = (v) => (v ? "β" : "-");
return `
<section>
<h2>Overview</h2>
<dl class="kv">
<dt>Geometry</dt><dd>${info.geometryType}</dd>
<dt>Features</dt><dd>${info.count?.toLocaleString() ?? "unknown"}</dd>
<dt>OID field</dt><dd>${info.objectIdField}</dd>
<dt>Display field</dt><dd>${info.displayField ?? "-"}</dd>
<dt>Spatial ref</dt><dd>EPSG:${info.spatialReference}</dd>
<dt>Renderer</dt><dd>${info.rendererType}</dd>
</dl>
</section>
<section>
<h2>Capabilities</h2>
<dl class="kv">
<dt>Query</dt><dd>${yes(info.capabilities.query)}</dd>
<dt>Add / Update / Delete</dt>
<dd>${yes(info.capabilities.add)} ${yes(info.capabilities.update)} ${yes(info.capabilities.delete)}</dd>
<dt>Statistics</dt><dd>${yes(info.capabilities.statistics)}</dd>
<dt>Pagination</dt><dd>${yes(info.capabilities.pagination)}</dd>
<dt>Attachments</dt><dd>${yes(info.capabilities.attachments)}</dd>
<dt>Max records</dt><dd>${info.capabilities.maxRecordCount ?? "-"}</dd>
</dl>
</section>
<section>
<h2>Fields (${info.fields.length})</h2>
<table class="fields">
<thead><tr><th>Name</th><th>Type</th><th>Alias</th></tr></thead>
<tbody>
${info.fields.map((f) => `
<tr>
<td><code>${f.name}</code></td>
<td>${f.type}${f.length ? `(${f.length})` : ""}</td>
<td>${f.alias ?? ""}${f.domain ? `<br><small>${f.domain}</small>` : ""}</td>
</tr>`).join("")}
</tbody>
</table>
</section>
`;
}
extent.expand(1.1) adds 10% padding so features aren't flush against the viewport edge.
Small touch, noticeably better.
.catch(() => {}) on goTo - the user might pan during the flight; that rejection is
expected and not worth logging.
Step 4 - Test it on real services
Paste each of these in and read the report:
# A big point layer with domains
https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_Major_Cities/FeatureServer/0
# Polygons, many numeric fields - good choropleth candidate
https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_Counties_Generalized/FeatureServer/0
# Lines
https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_Freeway_System/FeatureServer/2
# Deliberately wrong - no layer index. Read the error.
https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_Major_Cities/FeatureServer
# Deliberately wrong - doesn't exist
https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/NotAThing/FeatureServer/0
Then find your own city's open data portal on https://hub.arcgis.com/ and inspect three of its layers. Real data is messier than samples, which is the point.
Step 5 - Add outFields control
Add a multi-select of the field list, and rebuild the layer with only the selected fields.
function applyOutFields(layer, selectedNames) {
// Always include the OID - the SDK needs it for identity, and dropping it
// breaks highlight, popups and client-side query.
const fields = Array.from(new Set([layer.objectIdField, ...selectedNames]));
layer.outFields = fields;
layer.refresh();
}
Measure the difference. With DevTools' Network tab open, load the counties layer with
["*"] and then with three fields. Compare the response sizes of the /query requests.
On a wide table this is routinely a 5-10Γ reduction. It is the cheapest performance improvement in this entire course.
How it works
What load() actually requests
One GET to the layer's REST endpoint with f=json:
https://services.arcgis.com/.../FeatureServer/0?f=json
The response is the layer's metadata document: fields, geometryType, extent,
drawingInfo (the server's default renderer), capabilities, maxRecordCount,
supportedQueryFormats, and more.
You can open that URL in a browser. Doing so once, for a service you're fighting with, is
usually faster than any amount of console.log. Everything the layer knows is in there.
Why the renderer sometimes appears without you setting one
The service metadata contains drawingInfo, the symbology the publisher saved in ArcGIS Pro
or Online. load() converts it into a renderer and assigns it. That is why a layer often looks
"right" before you touch it.
Set layer.renderer yourself and you replace it. Set layer.renderer = null, and the SDK
falls back to a default symbol for the geometry type.
Why definitionExpression is different from every other filter
It is sent to the server as part of the query's where. The server never returns the excluded
features, so:
- Less data over the wire
queryFeatureCount()reflects the filter- The legend can reflect it
- It affects every view of the layer, because it changes the data, not a rendering
That last point matters when two views share a layer (Module 05, Exercise 05.4) and is why
FeatureFilter exists (Module 21).
It also persists outside React. layer.definitionExpression lives on the layer object; a
component that sets it and unmounts leaves the filter applied. This repository documents that
as gotcha #4 and handles it with restore-on-unmount effects. You will meet it in Module 21 and
again in Module 37.
Why outFields affects things that seem unrelated
Field values are only in the browser if they were requested. So:
- A popup with
{POPULATION}shows the literal text ifPOPULATIONwasn't downloaded - A renderer keyed on a field silently falls back to the default symbol
layerView.queryFeatures()returnsundefinedfor the field- An Arcade expression referencing
$feature.FIELDerrors
All four look like different bugs. They are one bug.
Common mistakes
Reading layer.fields before await layer.load().
null. This is the module's rite of passage.
Hardcoding "OBJECTID".
Read layer.objectIdField. Services published from different sources use FID, ObjectId,
esri_oid.
Using outFields: ["*"] in production.
Works, and is slow in a way you won't notice until the layer has 40 fields and 200k features.
Confusing the service URL with the layer URL.
/FeatureServer is the service. /FeatureServer/0 is a layer.
Setting minScale and maxScale backwards.
minScale is the zoomed-out limit and the larger number.
Assuming a service supports editing because you can see it.
Check capabilities.operations.
Not handling the load failure.
An unhandled rejection from layer.load() gives you a blank map and a console message you'll
scroll past.
Exercises
Exercise 08.1 - Finish the inspector
Add to your tool:
- A field-type summary (
5 string, 8 double, 2 date) - A "copy as code" button that emits a ready-to-paste
new FeatureLayer({...})snippet with the URL, title and a sensibleoutFields - Sample values: query 5 features and show the first few values per field
- A warning when
outFieldsis["*"]and the layer has more than 15 fields
Exercise 08.2 - Scale-dependent visibility
Load the US counties layer and the US cities layer together. Configure:
- Counties visible only when zoomed out beyond 1:5,000,000
- Cities visible only when zoomed in past 1:5,000,000
Then watch the Network tab as you zoom across the boundary. Write down what you observe about requests. What does this tell you about the performance value of scale ranges?
Exercise 08.3 - Errors on purpose
Trigger each of these and record the exact error message:
- A URL missing the layer index
- A non-existent service
- A secured service with no token (find one on ArcGIS Online - plenty of items are private)
- A URL with a typo in the domain (CORS/DNS failure)
outFieldsnaming a field that doesn't exist
Build a lookup table of message β cause β fix. You are constructing your own debugging index, which is worth more than reading someone else's.
Exercise 08.4 - outFields measured
Using the counties layer, produce a table:
| outFields | # fields | /query response size |
Time to first draw |
|---|---|---|---|
["*"] |
|||
| 10 fields | |||
| 3 fields | |||
| OID only |
Then state the guidance you'd give a colleague, in one sentence.
Checkpoint
- Why is
layer.fieldsnull immediately afternew FeatureLayer()? - What's the difference between a
FeatureServerURL and aFeatureServer/0URL? - Your popup shows
{POPULATION}as literal text. What's wrong? - Which of
minScale/maxScaleis the zoomed-out limit, and what's the bigger number? - How do you know whether a service allows editing?
- Why does
definitionExpressionaffect both views when two views share a layer, butlayerView.filterdoesn't? - Where does a layer's renderer come from if you never set one?
- The constructor doesn't fetch anything. Metadata arrives from
load(), which is one request to the service's?f=jsonendpoint. - The first is the service (a container). The second is a layer within it. Layer operations need the index.
POPULATIONisn't inoutFields, so the value was never downloaded and there is nothing to substitute.minScaleis the zoomed-out limit, and it's the larger number (scale denominators grow as you zoom out).await layer.load(), then checklayer.capabilities.operations.supportsAdd/supportsUpdate/supportsDelete.definitionExpressionchanges the server query, so the data itself differs - every view sees the result.layerView.filterhides already-downloaded features in one view's rendering.- From the service metadata's
drawingInfo, which holds the symbology the publisher saved.
Further reading
- https://developers.arcgis.com/javascript/latest/api-reference/esri-layers-FeatureLayer.html - read the whole property list once
- https://developers.arcgis.com/rest/services-reference/enterprise/layer-feature-service/ -
the metadata document you get from
?f=json - https://developers.arcgis.com/javascript/latest/sample-code/layers-featurelayer/