Module 09 - The Layer Zoo

Level 2 · Layers & Data · 🟡 · 4 hours · Prereq: Module 08


What you'll build

A multi-format loader: give it a URL or a file and it works out what layer type to use and adds it to the map. Handles feature services, GeoJSON, CSV, tile services, vector tiles, imagery, OGC (WMS/WFS/WMTS), KML and GeoRSS.

This is a reference module. Do not try to memorise fifteen layer types. Learn the decision procedure, and come back to the table when you need it.


Why this matters

The most common real-world task in web GIS is "here is a data source, put it on the map." The skill is not writing the layer - it is identifying what you've been handed in thirty seconds rather than an afternoon.


Concepts

1. The decision table

You have Use Notes
.../FeatureServer/0 FeatureLayer The default. Queryable, editable
.../MapServer (whole) MapImageLayer Server renders images; sublayers toggleable
.../MapServer/2 (one layer) FeatureLayer Works if the service supports query
.../MapServer cached TileLayer Pre-rendered raster tiles
.../VectorTileServer VectorTileLayer Styled client-side
.../SceneServer SceneLayer 3D. Buildings, points, meshes
.../ImageServer ImageryLayer or ImageryTileLayer Dynamic vs cached
.../ImageServer (elevation) ElevationLayer Goes in map.ground, not map.layers
.../StreamServer StreamLayer WebSocket live feed
.geojson URL or file GeoJSONLayer Always WGS84
.csv with lat/lon columns CSVLayer
.kml / .kmz KMLLayer Needs a CORS-enabled host
.geojson from a non-CORS API fetch + FeatureLayer({ source }) Fetch it yourself, build client-side
A WMS endpoint WMSLayer OGC. Server-rendered images
A WMTS endpoint WMTSLayer OGC. Cached tiles
A WFS endpoint WFSLayer OGC. Real features
An OGC API - Features endpoint OGCFeatureLayer The modern OGC vector standard
A georeferenced image/PNG MediaLayer Pin an image to map coordinates
Graphics you made GraphicsLayer No query, no popup templates per-layer
An array of objects from any API FeatureLayer({ source }) Underused. See Module 10
Several layers to manage together GroupLayer
Your own tile scheme WebTileLayer {z}/{x}/{y} URL template
A portal item, type unknown Layer.fromPortalItem() The SDK picks the class

2. How to identify a service URL

Every ArcGIS REST endpoint self-describes. Open it in a browser tab.

https://services.arcgis.com/xxx/arcgis/rest/services/MyData/FeatureServer
                                                              ^^^^^^^^^^^^^ the type

The last path segment before any layer index tells you everything:

Segment Layer class
FeatureServer FeatureLayer (per sublayer)
MapServer MapImageLayer (dynamic) or TileLayer (cached - check singleFusedMapCache: true)
VectorTileServer VectorTileLayer
SceneServer SceneLayer
ImageServer ImageryLayer / ImageryTileLayer / ElevationLayer
StreamServer StreamLayer
GPServer Not a layer - a geoprocessing service
GeocodeServer Not a layer - a locator (Module 22)
NAServer Not a layer - network analysis (Module 27)

And when you truly don't know:

import Layer from "@arcgis/core/layers/Layer.js";

const layer = await Layer.fromArcGISServerUrl({ url });
map.add(layer);
console.log(layer.type, layer.declaredClass);

Layer.fromArcGISServerUrl() inspects the endpoint and returns the right class. Use it in tooling; be explicit in application code, because explicit is debuggable.

3. The four you'll use most, in detail

GeoJSONLayer

import GeoJSONLayer from "@arcgis/core/layers/GeoJSONLayer.js";

const quakes = new GeoJSONLayer({
  url: "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson",
  title: "Earthquakes, past day",
  copyright: "USGS",

  // GeoJSON has no OBJECTID. The SDK generates one unless you name a field.
  objectIdField: "ObjectID",

  // Optional but strongly recommended: declare the schema so renderers and
  // popups know the types instead of inferring from the first feature.
  fields: [
    { name: "ObjectID", type: "oid" },
    { name: "mag",      type: "double", alias: "Magnitude" },
    { name: "place",    type: "string", alias: "Location" },
    { name: "time",     type: "date",   alias: "Time" },
    { name: "depth",    type: "double", alias: "Depth (km)" },
  ],

  renderer: {
    type: "simple",
    symbol: { type: "simple-marker", color: "#d73027", outline: { color: "white", width: 0.5 } },
  },
  popupTemplate: { title: "{place}", content: "M{mag} at {depth} km" },
});

Three constraints to know:

  1. The URL must be CORS-enabled. USGS is; many APIs aren't. If it isn't, fetch it yourself and use a client-side FeatureLayer (Module 10).
  2. GeoJSON is always WGS84 per RFC 7946. The SDK projects it for display.
  3. Type inference from the first feature is a trap. If feature 1 has mag: null, the field may be inferred as string, and your numeric renderer silently fails. Declare fields.

CSVLayer

import CSVLayer from "@arcgis/core/layers/CSVLayer.js";

const stations = new CSVLayer({
  url: "/data/stations.csv",
  title: "Monitoring stations",
  latitudeField: "lat",       // auto-detected if named lat/latitude/y
  longitudeField: "lon",
  delimiter: ",",
  popupTemplate: { title: "{name}", content: "Reading: {value} {unit}" },
});

Everything arrives as a string unless you declare fields. A "numeric" column you didn't declare will not drive a class-breaks renderer.

VectorTileLayer

import VectorTileLayer from "@arcgis/core/layers/VectorTileLayer.js";

const layer = new VectorTileLayer({
  url: "https://basemaps.arcgis.com/arcgis/rest/services/World_Basemap_v2/VectorTileServer",
});

// Restyle at runtime - this is the superpower
await layer.when();
layer.setPaintProperties("Water area", { "fill-color": "#0a1e3a" });
layer.setLayoutProperties("Road/Street", { visibility: "none" });

setPaintProperties / setLayoutProperties take a style layer name from the style JSON and Mapbox-GL-style property objects. Open the service's /resources/styles/root.json to find the names.

Not queryable. Vector tiles carry attributes for styling, not for analysis. If you need to click a road and get its record, you need a FeatureLayer alongside.

ImageryLayer / ImageryTileLayer

import ImageryLayer from "@arcgis/core/layers/ImageryLayer.js";

const landsat = new ImageryLayer({
  url: "https://landsat2.arcgis.com/arcgis/rest/services/Landsat/MS/ImageServer",
  format: "jpgpng",

  // Band math on the server: NDVI = (NIR − Red) / (NIR + Red)
  // Landsat 8: band 4 = Red (index 3), band 5 = NIR (index 4)
  rasterFunction: {
    functionName: "NDVI",
    functionArguments: { VisibleBandID: 3, InfraredBandID: 4 },
    variableName: "Raster",
  },
});
ImageryLayer ImageryTileLayer
Rendering Server renders per request Cached tiles, client renders
Raster functions Server-side, any function Client-side, limited set
Pixel access layer.identify() for values fetchPixels() for the array
Performance Slower, flexible Faster, fixed

4. GroupLayer - structure, not decoration

import GroupLayer from "@arcgis/core/layers/GroupLayer.js";

const infrastructure = new GroupLayer({
  title: "Infrastructure",
  visibilityMode: "independent",   // "exclusive" = radio buttons, "inherited" = follow parent
  layers: [waterLayer, sewerLayer, electricLayer],
  opacity: 0.9,
});
map.add(infrastructure);

The consequence that catches people: map.layers is not flat. A group's children are not in it.

map.layers.find((l) => l.title === "Water");        // undefined if it's in a group
map.allLayers.find((l) => l.title === "Water");     // ✅ flattened, includes children

map.allLayers is the one you want in nearly every "find a layer" situation. This repository documents exactly this - it exports its own findLayerById(map, id) walking allLayers because Map.findLayerById isn't documented to search nested layers, and a Waterbody layer inside a group is the normal case.

5. Layer order and map.add

map.add(layer);              // top of the stack
map.add(layer, 0);           // bottom
map.addMany([a, b, c]);
map.reorder(layer, 2);
map.remove(layer);
map.removeAll();

Drawing order is bottom of map.layers first. So index 0 draws first (underneath), and the last item draws last (on top). Polygons under lines under points is almost always what you want.

GraphicsLayer on top - a highlight layer that ends up under your data is invisible and looks like a bug in your highlight code.

6. Layer.fromPortalItem - the generic loader

import Layer from "@arcgis/core/layers/Layer.js";

const layer = await Layer.fromPortalItem({ portalItem: { id: "abc123..." } });
map.add(layer);

The SDK reads the item's type and constructs the right class. Ideal for a "add layer by item id" UI where you don't know what the user will paste.


Build it - the multi-format loader

Step 1 - Detect the type

// src/layerFactory.js
import FeatureLayer from "@arcgis/core/layers/FeatureLayer.js";
import GeoJSONLayer from "@arcgis/core/layers/GeoJSONLayer.js";
import CSVLayer from "@arcgis/core/layers/CSVLayer.js";
import VectorTileLayer from "@arcgis/core/layers/VectorTileLayer.js";
import TileLayer from "@arcgis/core/layers/TileLayer.js";
import MapImageLayer from "@arcgis/core/layers/MapImageLayer.js";
import ImageryLayer from "@arcgis/core/layers/ImageryLayer.js";
import WMSLayer from "@arcgis/core/layers/WMSLayer.js";
import WMTSLayer from "@arcgis/core/layers/WMTSLayer.js";
import WFSLayer from "@arcgis/core/layers/WFSLayer.js";
import OGCFeatureLayer from "@arcgis/core/layers/OGCFeatureLayer.js";
import KMLLayer from "@arcgis/core/layers/KMLLayer.js";
import Layer from "@arcgis/core/layers/Layer.js";

/**
 * Best-effort detection of what kind of layer a URL represents.
 * Returns a short type key; "unknown" means we should probe the endpoint.
 */
export function detectLayerType(url) {
  const u = url.toLowerCase();

  // File extensions first - unambiguous
  if (u.endsWith(".geojson") || u.endsWith(".json") && u.includes("geojson")) return "geojson";
  if (u.endsWith(".csv"))  return "csv";
  if (u.endsWith(".kml") || u.endsWith(".kmz")) return "kml";

  // ArcGIS REST service types
  if (u.includes("/featureserver")) return "feature";
  if (u.includes("/vectortileserver")) return "vectortile";
  if (u.includes("/sceneserver")) return "scene";
  if (u.includes("/imageserver")) return "imagery";
  if (u.includes("/streamserver")) return "stream";
  if (u.includes("/mapserver")) return "mapserver";   // tile or dynamic - probe to decide

  // OGC - usually identified by query parameters
  if (u.includes("service=wms")) return "wms";
  if (u.includes("service=wmts") || u.includes("/wmts")) return "wmts";
  if (u.includes("service=wfs")) return "wfs";
  if (u.includes("/collections")) return "ogcfeature";   // OGC API - Features

  return "unknown";
}

/**
 * Build a layer from a URL, choosing the class by detected type.
 * @param {string} url
 * @param {object} [options] extra properties merged into the layer
 */
export async function createLayerFromUrl(url, options = {}) {
  const type = detectLayerType(url);

  switch (type) {
    case "geojson":
      return new GeoJSONLayer({ url, ...options });

    case "csv":
      return new CSVLayer({ url, ...options });

    case "kml":
      return new KMLLayer({ url, ...options });

    case "feature":
      // A bare /FeatureServer with no index isn't a layer - load all its sublayers.
      return /\/featureserver\/\d+/i.test(url)
        ? new FeatureLayer({ url, outFields: ["*"], ...options })
        : await Layer.fromArcGISServerUrl({ url });

    case "vectortile":
      return new VectorTileLayer({ url, ...options });

    case "imagery":
      return new ImageryLayer({ url, ...options });

    case "mapserver":
      return await createMapServerLayer(url, options);

    case "wms":   return new WMSLayer({ url, ...options });
    case "wmts":  return new WMTSLayer({ url, ...options });
    case "wfs":   return new WFSLayer({ url, ...options });
    case "ogcfeature": return new OGCFeatureLayer({ url, ...options });

    case "scene":
    case "stream":
      // Both need imports that drag in large dependencies; load on demand.
      return await createHeavyLayer(type, url, options);

    default:
      // Let the SDK probe the endpoint and decide.
      return await Layer.fromArcGISServerUrl({ url });
  }
}

/**
 * A MapServer is either a cached tile service or a dynamic map service.
 * `singleFusedMapCache` in the service metadata tells us which.
 */
async function createMapServerLayer(url, options) {
  const response = await fetch(`${url}?f=json`);
  const meta = await response.json();
  return meta.singleFusedMapCache
    ? new TileLayer({ url, ...options })
    : new MapImageLayer({ url, ...options });
}

/**
 * SceneLayer pulls in the 3D stack and StreamLayer the websocket stack.
 * Dynamic import keeps both out of the main bundle.
 */
async function createHeavyLayer(type, url, options) {
  if (type === "scene") {
    const { default: SceneLayer } = await import("@arcgis/core/layers/SceneLayer.js");
    return new SceneLayer({ url, ...options });
  }
  const { default: StreamLayer } = await import("@arcgis/core/layers/StreamLayer.js");
  return new StreamLayer({ url, ...options });
}

Read createMapServerLayer again. It is the only case that needs a network probe, because MapServer is genuinely ambiguous. That is the kind of detail that separates a loader that works from one that works on the samples.

The dynamic imports in createHeavyLayer are not decoration. SceneLayer reaches the 3D renderer; importing it statically adds ~500 KB to a 2D app that may never load a scene.

Step 2 - Wire it up with error reporting

// src/main.js
import { createLayerFromUrl, detectLayerType } from "./layerFactory.js";

const loadedLayers = [];

async function addLayer(url) {
  const type = detectLayerType(url);
  setStatus(`Detected "${type}" - loading…`, "busy");

  try {
    const layer = await createLayerFromUrl(url, { title: labelFor(url) });
    await layer.load();

    mapEl.view.map.add(layer);
    loadedLayers.push(layer);

    // Zoom to it if it knows where it is
    if (layer.fullExtent) {
      await mapEl.view.goTo(layer.fullExtent.expand(1.1)).catch(() => {});
    }

    setStatus(`Added ${layer.title ?? "layer"} (${layer.type})`, "ok");
    renderLayerList();
  } catch (error) {
    setStatus(`Failed: ${error.message}`, "error");
    console.error(error);
  }
}

const labelFor = (url) => decodeURIComponent(url.split("/").filter(Boolean).slice(-2).join(" / "));

Step 3 - Handle dropped files

const dropZone = document.getElementById("dropZone");

dropZone.addEventListener("dragover", (event) => {
  event.preventDefault();
  dropZone.classList.add("dropZone--over");
});

dropZone.addEventListener("dragleave", () => dropZone.classList.remove("dropZone--over"));

dropZone.addEventListener("drop", async (event) => {
  event.preventDefault();
  dropZone.classList.remove("dropZone--over");

  for (const file of event.dataTransfer.files) {
    await addLocalFile(file);
  }
});

async function addLocalFile(file) {
  const name = file.name.toLowerCase();

  if (name.endsWith(".geojson") || name.endsWith(".json")) {
    const text = await file.text();
    const geojson = JSON.parse(text);

    // GeoJSONLayer needs a URL, so make one from the file contents.
    // The blob URL lives until we revoke it - hold on to it if the layer is long-lived.
    const blob = new Blob([JSON.stringify(geojson)], { type: "application/json" });
    const url = URL.createObjectURL(blob);

    const { default: GeoJSONLayer } = await import("@arcgis/core/layers/GeoJSONLayer.js");
    const layer = new GeoJSONLayer({ url, title: file.name });
    await layer.load();
    mapEl.view.map.add(layer);
    // Note: do NOT revokeObjectURL here - the layer re-reads the URL when it refreshes.
    return;
  }

  if (name.endsWith(".csv")) {
    const blob = new Blob([await file.text()], { type: "text/csv" });
    const { default: CSVLayer } = await import("@arcgis/core/layers/CSVLayer.js");
    const layer = new CSVLayer({ url: URL.createObjectURL(blob), title: file.name });
    await layer.load();
    mapEl.view.map.add(layer);
    return;
  }

  setStatus(`Unsupported file type: ${file.name}`, "error");
}

The URL.createObjectURL trick turns an in-memory file into something the layer classes can fetch. The comment about not revoking is a real bug: revoke it and the layer breaks the next time it refreshes, with an error that points nowhere near the drop handler.

Step 4 - Test the zoo

# FeatureLayer
https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_Major_Cities/FeatureServer/0

# GeoJSON (live)
https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson

# Tile (cached MapServer)
https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer

# Dynamic MapServer - same URL shape, different class. This is why we probe.
https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer

# VectorTileLayer
https://basemaps.arcgis.com/arcgis/rest/services/World_Basemap_v2/VectorTileServer

# ImageryLayer
https://landsat2.arcgis.com/arcgis/rest/services/Landsat/MS/ImageServer

# WMS (public)
https://ows.terrestris.de/osm/service?SERVICE=WMS&REQUEST=GetCapabilities

Load each, note what type your detector chose, and whether it was right.


How it works

Why MapServer needs a probe

A MapServer publishes both a dynamic interface (render me this extent now) and, if the publisher built a cache, a tiled interface. The service metadata's singleFusedMapCache boolean is the only reliable discriminator.

Guess wrong and you get either terrible performance (dynamic rendering when tiles exist) or a blank layer (asking for tiles that were never generated).

Why GeoJSON type inference fails

GeoJSONLayer reads the first feature to build a schema. Given:

{ "properties": { "mag": null, "place": "10km E of Ridgecrest" } }

mag is null, so its type is unknowable. The SDK guesses - often string. Then your class-breaks renderer on mag finds no numeric field and silently renders defaults.

Declaring fields explicitly fixes it. The five extra lines are worth it every time.

Why some layers can't be queried

Layer Queryable? Why
FeatureLayer ✅ Backed by a table with a spatial index
GeoJSONLayer / CSVLayer ✅ Fully loaded into memory client-side
WFSLayer / OGCFeatureLayer ✅ Real features over an OGC protocol
VectorTileLayer ❌ Tiles are for styling; attributes are per-tile fragments, not records
TileLayer / WMTSLayer ❌ Pixels
MapImageLayer ⚠️ Its sublayers may support query if the service allows it
ImageryLayer ⚠️ identify() gives you pixel values, not features
GraphicsLayer ❌ No query API - filter layer.graphics yourself

Design consequence: if the requirement is "user clicks a road and sees its attributes," a vector tile basemap alone will never do it. You need a FeatureLayer for the roads.

Why map.allLayers exists

map.layers is a Collection of top-level layers. map.allLayers is a computed, flattened Collection including every GroupLayer's children, recursively, and it stays in sync as groups change.

map.allLayers.filter((l) => l.type === "feature");
map.allLayers.find((l) => l.id === targetId);

Use it for anything that searches. Use map.layers only when you specifically mean top level.


Common mistakes

Using GeoJSONLayer with a non-CORS URL. Browser blocks it. Fetch server-side, proxy it, or fetch + client-side FeatureLayer.

Not declaring fields on GeoJSON/CSV layers. Types get inferred wrong and renderers fail silently.

Expecting VectorTileLayer to be queryable. It isn't. Pair it with a FeatureLayer.

Using map.layers.find() when layers are grouped. Use map.allLayers.

Adding an ElevationLayer to map.layers. It belongs in map.ground. In map.layers it renders as a grey raster and doesn't affect terrain. (Module 31.)

Statically importing SceneLayer in a 2D app. +500 KB for a class you might not construct.

Revoking an object URL a layer still depends on. It breaks on the next refresh, far from where you revoked it.


Exercises

Exercise 09.1 - Extend the loader

Add support for:

  1. Dropped shapefiles (.zip) - the SDK can't read these directly; find out what the ArcGIS "generate features" endpoint does and decide whether it's worth using. Write down your conclusion either way.
  2. A {z}/{x}/{y} template URL → WebTileLayer
  3. A portal item id (32 hex characters) → Layer.fromPortalItem
  4. A GeoJSON string pasted into a textarea

Exercise 09.2 - Identify ten URLs

For each, state the layer class without loading it, then verify:

1. https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_States_Generalized/FeatureServer/0
2. https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/NewYorkCity_Buildings/SceneServer
3. https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer
4. https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer
5. https://basemaps.arcgis.com/arcgis/rest/services/World_Basemap_v2/VectorTileServer
6. https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer
7. https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson
8. https://ows.terrestris.de/osm/service?SERVICE=WMS&REQUEST=GetCapabilities
9. https://demo.pygeoapi.io/master/collections/lakes
10. https://sampleserver6.arcgisonline.com/arcgis/rest/services/SF311/FeatureServer/0

Score yourself. Anything below 8/10 means re-read §2.

Exercise 09.3 - Live GeoJSON with proper fields

Load the USGS hourly earthquake feed with:

  • Explicit fields including a date type for time
  • A refresh every 60 seconds
  • A renderer sized by magnitude (peek at Module 15 if you like)
  • A popup showing a formatted local time

Then answer: what happens to the map when the feed updates? Do symbols flicker? What would you do about it?

Exercise 09.4 - Group layer structure

Build a map with three groups - Base Data, Infrastructure, Analysis - each with 2-3 layers.

Then:

  1. Write a function that finds a layer by title anywhere in the tree
  2. Write a function that collapses all groups
  3. Set one group to visibilityMode: "exclusive" and observe what the LayerList does
  4. Verify that map.layers.length is 3 while map.allLayers.length is 3 + children

Checkpoint

  1. You're given https://example.com/arcgis/rest/services/Roads/MapServer. What layer class, and how do you decide?
  2. Why can't you query a VectorTileLayer?
  3. Your GeoJSON layer's class-breaks renderer shows all features in the default symbol. What's the likely cause?
  4. Where does an ElevationLayer go?
  5. What's the difference between map.layers and map.allLayers?
  6. Which draws on top - index 0 or the last index?
  7. Name two layer types that need a dynamic import in a 2D app, and why.
  1. Either TileLayer or MapImageLayer. Fetch ?f=json and check singleFusedMapCache: true → cached tiles → TileLayer; false → dynamic → MapImageLayer.
  2. Vector tiles carry geometry fragments and styling attributes per tile, not records with identity. There is no queryable table behind them.
  3. The field's type was inferred as string because the first feature's value was null or a string. Declare fields explicitly.
  4. map.ground.layers. In map.layers it renders as a grey image and doesn't deform terrain.
  5. map.layers is top-level only; map.allLayers is a flattened, live collection including every GroupLayer's descendants.
  6. The last index draws on top. Index 0 is the bottom of the stack.
  7. SceneLayer (pulls the 3D renderer) and StreamLayer (pulls the WebSocket/real-time stack). Both add large dependency subtrees you don't want in a 2D bundle.

Further reading


Next: Module 10 - Graphics and Client-Side Data