Module 05 - Map and View: the Anatomy

Level 1 ยท Your First Maps ยท ๐ŸŸข Beginner ยท 3 hours ยท Prereq: Module 04


What you'll build

A camera control panel: bookmark buttons that fly the view to saved locations, a live readout of centre/zoom/scale/rotation/extent, and a "share this view" link that encodes the camera into a URL and restores it on load.

Along the way you will build a precise mental model of what belongs to the Map and what belongs to the View, which is the thing that makes the rest of the SDK make sense.


Why this matters

Nearly every "where do I put this?" question in the SDK is answered by the Map/View split:

  • Where does a layer go? โ†’ Map (it's data)
  • Where does a filter go? โ†’ LayerView (it's per-view presentation)
  • Where does the camera go? โ†’ View
  • Where does a popup template go? โ†’ Layer (it's a property of the data's schema)
  • Where does the popup itself go? โ†’ View
  • What gets saved into a WebMap? โ†’ Map, not the camera... except the initial extent, which is saved separately as part of the item

Get the split wrong and you write code that works in one view and mysteriously doesn't in another, or that "loses" state on a view rebuild.


Concepts

1. The split

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Map โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  basemap      Basemap        (reference layers under data)  โ”‚
โ”‚  ground       Ground         (elevation layers, 3D only)    โ”‚
โ”‚  layers       Collection<Layer>   (your operational data)   โ”‚
โ”‚  tables       Collection<Layer>   (non-spatial tables)      โ”‚
โ”‚                                                             โ”‚
โ”‚  NO camera. NO container. NO events about rendering.        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                             โ”‚
                    displayed by 1..n
                             โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ MapView / SceneView โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  container            the DOM element                       โ”‚
โ”‚  map                  โ† the model above                     โ”‚
โ”‚  center / zoom / scale / rotation      (MapView)            โ”‚
โ”‚  camera                                (SceneView)          โ”‚
โ”‚  extent               current viewport in map coords        โ”‚
โ”‚  spatialReference     inherited from the basemap            โ”‚
โ”‚  ui                   widget placement manager              โ”‚
โ”‚  graphics             view-only overlay graphics            โ”‚
โ”‚  popup / popupEnabled                                       โ”‚
โ”‚  allLayerViews        Collection<LayerView>                 โ”‚
โ”‚  constraints          zoom limits, rotation lock, snapping  โ”‚
โ”‚  padding              inset for UI overlays                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The one-sentence version: the Map is what, the View is where you're looking from and how it's drawn.

2. Map, WebMap, WebScene

Three classes, one relationship:

// Built in code
const map = new Map({ basemap: "arcgis/navigation" });

// Loaded from a saved ArcGIS Online item - layers, symbology, popups, bookmarks all come with it
const webmap = new WebMap({ portalItem: { id: "e691172598f04ea8881cd2a4adaa45ba" } });

// The 3D equivalent, additionally carrying the ground, environment, and initial camera
const webscene = new WebScene({ portalItem: { id: "..." } });

WebMap and WebScene extend Map. Anything that accepts a Map accepts them. So:

const view = new MapView({ container: "viewDiv", map: webmap });
await webmap.when();           // wait for the item + all its layers
console.log(webmap.layers.length);

When to use which:

  • Map - you control the layers in code. Predictable, versioned with your app.
  • WebMap/WebScene - a non-developer configures the map in ArcGIS Online and your app just renders it. This is the model this repository uses: org_config.webscene_id points at an item that an admin configured.

3. MapView vs SceneView

MapView SceneView
Dimensions 2D 3D
Camera center + zoom/scale + rotation camera = { position, heading, tilt }
Terrain none map.ground
Modes - viewingMode: "global" | "local"
Bundle cost ~ +~500 KB
Layer support almost all almost all + SceneLayer, IntegratedMesh, PointCloud

They share a base class (View), so container, map, ui, graphics, popup, extent, goTo(), hitTest() and the event set are identical. Most of what you learn about one applies to the other. Level 6 covers the differences.

4. Camera properties in 2D

view.center      // Point - the map coordinate at the middle of the viewport
view.zoom        // number - tile pyramid level, may be fractional
view.scale       // number - the denominator: 36112 means 1:36,112
view.rotation    // degrees counter-clockwise, 0 = north up
view.extent      // Extent - the visible rectangle in map coordinates
view.resolution  // map units per pixel (read-only)

zoom and scale are two views of one value. Set either; both update.

view.zoom = 15;
console.log(view.scale);   // ~9027
view.scale = 5000;
console.log(view.zoom);    // ~15.85 - fractional, because 5000 isn't a pyramid level

zoom is only meaningful when there's a tiling scheme. With a non-tiled basemap or a custom spatial reference, zoom can be -1 and you must use scale. Prefer scale in code that must work anywhere.

5. goTo() - the only way you should move the camera

// Instant
view.center = [-79.383, 43.653];
view.zoom = 14;

// Animated, and it returns a Promise
await view.goTo({ center: [-79.383, 43.653], zoom: 14 });

goTo accepts a lot of target shapes:

await view.goTo(point);                          // a Geometry - centres on it
await view.goTo(extent);                         // an Extent - fits it
await view.goTo(graphic);                        // a Graphic - fits its geometry
await view.goTo(arrayOfGraphics);                // fits all of them
await view.goTo({ target: geometry, zoom: 16 }); // geometry + explicit zoom
await view.goTo({ center: [x, y], scale: 5000, rotation: 45 });
await view.goTo(target, { duration: 2000, easing: "ease-in-out" });

goTo rejects when interrupted. If the user pans while an animation is running, or you start a second goTo, the first Promise rejects with a view:goto-interrupted error. That is normal behaviour, not a bug - but an unhandled rejection will spam your console:

view.goTo(target).catch((error) => {
  if (error.name !== "AbortError") console.error(error);
});

Get in the habit now. It comes up constantly in Level 4.

6. padding - the property nobody discovers until too late

If your UI has a 320 px sidebar, the visual centre of the map is not the centre of the container. goTo will centre things behind your sidebar.

view.padding = { top: 0, right: 0, bottom: 0, left: 320 };

Now center, goTo, popup placement and the Home widget all account for it. One line; saves a lot of manual offset maths.

7. constraints

view.constraints = {
  minZoom: 10,
  maxZoom: 18,
  rotationEnabled: false,
  snapToZoom: false,       // allow fractional zoom while wheel-scrolling
  geometry: cityBoundary,  // clamp panning to this area
};

geometry is the one worth knowing: it keeps the user inside your data's extent so they can't pan to the Pacific and wonder where the map went.

8. view.ui - the widget manager

view.ui.add(widget, "top-right");
view.ui.add([w1, w2], "bottom-left");
view.ui.add({ component: widget, position: "top-left", index: 0 });
view.ui.move(widget, "bottom-right");
view.ui.remove(widget);
view.ui.empty("top-left");                 // remove everything in a position
view.ui.components = ["zoom", "compass"];  // replace the default set entirely

The defaults are ["zoom", "navigation-toggle", "compass", "attribution"] for MapView. Removing "attribution" may violate your data licence - Esri basemaps require it. Move it if you must; don't delete it.

view.ui.add(domElement, "manual") lets you overlay arbitrary HTML positioned by your own CSS.

9. view.graphics vs GraphicsLayer

view.graphics.add(graphic);       // this view only, not in map.layers, no LayerView
const layer = new GraphicsLayer({ title: "My drawings" });
map.add(layer);
layer.graphics.add(graphic);      // in every view of the map, appears in LayerList,
                                  // has a LayerView, respects layer order and opacity

Rule: view.graphics for ephemeral things (a hover highlight, a temporary crosshair). GraphicsLayer for anything the user should be able to see in a legend, toggle, or reorder.

10. The lifecycle, again, with the missing piece

new Map()                    synchronous, cheap
new MapView({ map })         synchronous, starts async init
  โ””โ”€ await view.when()       view ready: extent, spatialReference, ui usable
       โ””โ”€ await view.whenLayerView(layer)
                             LayerView ready: filter, effect, highlight, client-side query
view.destroy()               tears down WebGL, layer views, handles

view.whenLayerView() is the piece people miss. The layer being in the map does not mean it is drawn or that you can filter it. Anything touching how a layer appears in this view needs the LayerView.


Build it - the camera control panel

Start from your Module 04 project.

Step 1 - Markup

index.html body:

<div id="viewDiv"></div>

<div id="panel">
  <h1>Camera</h1>

  <div class="group">
    <label>Bookmarks</label>
    <div id="bookmarks" class="buttons"></div>
  </div>

  <div class="group">
    <label>State</label>
    <dl id="readout">
      <dt>center</dt><dd id="r-center">-</dd>
      <dt>zoom</dt><dd id="r-zoom">-</dd>
      <dt>scale</dt><dd id="r-scale">-</dd>
      <dt>rotation</dt><dd id="r-rotation">-</dd>
      <dt>resolution</dt><dd id="r-resolution">-</dd>
    </dl>
  </div>

  <div class="group">
    <button id="copyLink" type="button">Copy link to this view</button>
    <span id="copied" hidden>Copied</span>
  </div>
</div>

CSS (append to style.css):

#panel { width: 280px; }
#panel .group { margin-top: 14px; }
#panel label {
  display: block; font-size: 11px; text-transform: uppercase;
  letter-spacing: .06em; color: #888; margin-bottom: 6px;
}
#panel .buttons { display: flex; flex-wrap: wrap; gap: 6px; }
#panel button {
  font: inherit; font-size: 13px; padding: 6px 10px; cursor: pointer;
  border: 1px solid #d0d0d0; background: #fafafa; border-radius: 6px;
}
#panel button:hover { background: #f0f0f0; }
#readout { display: grid; grid-template-columns: auto 1fr; gap: 2px 10px; margin: 0; font-size: 12px; }
#readout dt { color: #888; }
#readout dd { margin: 0; font-family: ui-monospace, "SF Mono", Consolas, monospace; }
#copied { font-size: 12px; color: #2a7; margin-left: 8px; }

Step 2 - Bookmarks with goTo

// src/bookmarks.js
export const BOOKMARKS = [
  { name: "Kingston",  center: [-76.481, 44.231], zoom: 13, rotation: 0 },
  { name: "Toronto",   center: [-79.383, 43.653], zoom: 12, rotation: 0 },
  { name: "Vancouver", center: [-123.116, 49.283], zoom: 12, rotation: 0 },
  { name: "Halifax",   center: [-63.573, 44.649], zoom: 13, rotation: 0 },
  { name: "World",     center: [0, 20],            zoom: 2,  rotation: 0 },
];
// src/main.js
import { BOOKMARKS } from "./bookmarks.js";

const bookmarksEl = document.getElementById("bookmarks");

for (const bookmark of BOOKMARKS) {
  const button = document.createElement("button");
  button.type = "button";
  button.textContent = bookmark.name;

  button.addEventListener("click", () => {
    view
      .goTo(
        { center: bookmark.center, zoom: bookmark.zoom, rotation: bookmark.rotation },
        { duration: 1200, easing: "ease-in-out" }
      )
      // A goTo interrupted by user input or another goTo rejects. That is expected;
      // swallow it so it doesn't fill the console.
      .catch((error) => {
        if (error.name !== "AbortError") console.error(error);
      });
  });

  bookmarksEl.append(button);
}

Why duration: 1200: the default is ~200 ms, which reads as a jump cut. Between roughly 800 and 1500 ms an animated fly-to reads as a spatial transition and helps users keep their bearings. Longer than 2 s and it feels slow.

Step 3 - The live readout

import * as reactiveUtils from "@arcgis/core/core/reactiveUtils.js";

const readout = {
  center: document.getElementById("r-center"),
  zoom: document.getElementById("r-zoom"),
  scale: document.getElementById("r-scale"),
  rotation: document.getElementById("r-rotation"),
  resolution: document.getElementById("r-resolution"),
};

const handle = reactiveUtils.watch(
  // 1. What to watch - a getter returning the values of interest
  () => [view.center, view.zoom, view.scale, view.rotation, view.resolution],

  // 2. What to do when any of them change
  ([center, zoom, scale, rotation, resolution]) => {
    readout.center.textContent =
      `${center.longitude.toFixed(4)}, ${center.latitude.toFixed(4)}`;
    readout.zoom.textContent = zoom.toFixed(2);
    readout.scale.textContent = `1:${Math.round(scale).toLocaleString()}`;
    readout.rotation.textContent = `${rotation.toFixed(1)}ยฐ`;
    readout.resolution.textContent = `${resolution.toFixed(3)} m/px`;
  },

  // 3. Options
  { initial: true }   // fire once immediately with the current values
);

How reactiveUtils.watch works: it runs the getter, records which SDK properties were touched, and re-runs the callback whenever any of them changes. You do not list dependencies - it detects them by observing property reads. Same idea as MobX or Vue's reactivity.

{ initial: true } fires the callback once at setup with the current values. Without it, your readout says "-" until the user moves the map.

The handle. watch returns { remove() }. In a plain script the page unload cleans up; in a component you must call handle.remove() or you leak. Module 18 and Module 37 make a meal of this. Start the habit now.

Step 4 - Share-a-view URL

function cameraToHash() {
  const { longitude, latitude } = view.center;
  const params = new URLSearchParams({
    lon: longitude.toFixed(6),
    lat: latitude.toFixed(6),
    z: view.zoom.toFixed(2),
    r: view.rotation.toFixed(1),
  });
  return `#${params}`;
}

function hashToCamera() {
  if (!location.hash) return null;
  const params = new URLSearchParams(location.hash.slice(1));
  const lon = Number(params.get("lon"));
  const lat = Number(params.get("lat"));
  const zoom = Number(params.get("z"));
  const rotation = Number(params.get("r") ?? 0);

  // Reject anything non-numeric or out of range rather than handing NaN to the view
  if (!Number.isFinite(lon) || !Number.isFinite(lat) || !Number.isFinite(zoom)) return null;
  if (Math.abs(lat) > 90 || Math.abs(lon) > 180) return null;

  return { center: [lon, lat], zoom, rotation };
}

// Restore on load - must run after the view is ready
view.when(() => {
  const restored = hashToCamera();
  if (restored) view.goTo(restored, { duration: 0 }).catch(() => {});
});

// Keep the hash in sync, but not on every frame
let hashTimer = null;
reactiveUtils.watch(
  () => view.stationary,
  (stationary) => {
    if (!stationary) return;
    clearTimeout(hashTimer);
    hashTimer = setTimeout(() => {
      history.replaceState(null, "", cameraToHash());
    }, 200);
  }
);

document.getElementById("copyLink").addEventListener("click", async () => {
  const url = `${location.origin}${location.pathname}${cameraToHash()}`;
  await navigator.clipboard.writeText(url);
  const badge = document.getElementById("copied");
  badge.hidden = false;
  setTimeout(() => { badge.hidden = true; }, 1500);
});

view.stationary is the property to know here. It is false while the view is animating or the user is dragging, and true when everything settles. Watching it is how you run expensive work (a query, a URL update, an analytics event) once per interaction instead of sixty times a second.

history.replaceState not pushState: pushState would add a browser history entry for every pan, and the back button would become useless.

The validation in hashToCamera matters. A user-editable URL is untrusted input. Passing NaN to view.goTo produces a view in an unrecoverable state that only a reload fixes.

Step 5 - Prove the Map/View split

Add a second view sharing the same map:

<div id="viewDiv"></div>
<div id="miniDiv"></div>
#viewDiv { position: absolute; inset: 0; }
#miniDiv {
  position: absolute; bottom: 16px; left: 16px;
  width: 220px; height: 160px; z-index: 10;
  border: 2px solid #fff; border-radius: 8px; overflow: hidden;
  box-shadow: 0 2px 10px rgba(0,0,0,.25);
}
const overview = new MapView({
  container: "miniDiv",
  map,                        // โ† the SAME map object
  center: view.center,
  zoom: 6,
  ui: { components: [] },     // no widgets in the mini view
  constraints: { rotationEnabled: false },
});

// Keep the overview centred on the main view, two levels out
reactiveUtils.watch(
  () => [view.center, view.zoom],
  ([center, zoom]) => {
    overview.goTo({ center, zoom: Math.max(zoom - 5, 2) }, { duration: 0 }).catch(() => {});
  }
);

Now test:

  1. Add a graphic to map.layers (via a GraphicsLayer) โ†’ appears in both
  2. Add a graphic to view.graphics โ†’ appears in the main view only
  3. Change view.zoom โ†’ the mini view follows because you wired it, not because it's automatic

That is the split, demonstrated. Keep this file.


How it works

Why watch doesn't need a dependency array

React's useEffect needs [deps] because it cannot see what you read - your callback is an opaque function. reactiveUtils.watch gets around this by running the getter in a tracking context: every Accessor property read during that call registers the getter as a dependent.

That is why the first argument must be a getter that reads the properties, and not the values themselves:

// โœ… reads view.zoom inside the tracked getter
reactiveUtils.watch(() => view.zoom, onZoom);

// โŒ reads it once, outside tracking - the callback never fires again
const z = view.zoom;
reactiveUtils.watch(() => z, onZoom);

Why one Map in two views is safe

Layers are stateless with respect to rendering. Everything view-specific - visible extent, filter, effect, highlight, tessellated geometry, tile cache - lives in the LayerView, one per (layer, view) pair.

So the second view creates its own LayerViews against the same Layer objects. Which is why:

  • layer.definitionExpression affects both views (it changes what the server returns)
  • layerView.filter affects one view (it changes what that view draws)

That distinction is Module 21 and it is worth a lot of marks in the L4 challenge.

Why view.extent and view.center can disagree with what you set

The view snaps to what it can actually render:

  • zoom snaps to a pyramid level if constraints.snapToZoom is true (the default)
  • center shifts if constraints.geometry clamps it
  • extent accounts for padding
  • scale is clamped by constraints.minScale/maxScale

So view.zoom = 15.7 may leave view.zoom === 16. Read back what you set if it matters.


Common mistakes

Reading view.extent before view.when(). null. Always.

Not catching goTo rejections. Every interrupted animation logs an unhandled rejection. In a bookmark UI, users interrupt constantly.

Using view.graphics for real data. No LayerView, no legend entry, no visibility toggle, no ordering. It also won't be there if you add a second view.

Forgetting padding with a sidebar. Everything is centred behind your UI and you fix it with magic-number offsets that break at another screen size.

Watching view.extent to trigger queries. It changes every animation frame. Watch view.stationary instead, or debounce.

Setting view.center inside a watch on view.center. Infinite loop. The SDK will not stop you.


Exercises

Exercise 05.1 - Extent bookmarks

Change the bookmarks to store an Extent instead of centre+zoom, and goTo the extent.

Then answer: why is an extent a better bookmark format than centre+zoom for a responsive layout? (Hint: resize the window with each version and watch what happens.)

Exercise 05.2 - Constrain the map

Add constraints so the user cannot:

  • Zoom out beyond scale 1:500,000
  • Zoom in beyond 1:1,000
  • Rotate the map
  • Pan outside Ontario

For the last one you need a geometry. Get one from the states/provinces service in RESOURCES.md, or use a hard-coded extent. Both approaches are valid - note the trade-off in a comment.

Exercise 05.3 - A camera history stack

Add Back / Forward buttons that step through the view states the user has visited.

Requirements:

  • Push a state only when view.stationary becomes true and the camera actually moved more than a threshold (or you'll push dozens of near-identical entries)
  • Don't push when the move was caused by Back/Forward itself (you need a flag)
  • Cap the stack at 50

This is harder than it looks and teaches you a lot about stationary.

Exercise 05.4 - Which container?

For each item, say whether it belongs to the Map, the View, the Layer, or the LayerView:

  1. A FeatureLayer's URL
  2. The current zoom level
  3. Whether a layer is visible in the legend
  4. A client-side filter hiding features in one of two views
  5. A popup template
  6. The basemap
  7. The list of widgets in the top-right
  8. A definitionExpression
  9. Terrain elevation
  10. A highlight on a selected feature
  1. Layer ยท 2. View ยท 3. Layer (legendEnabled, listMode) ยท 4. LayerView (filter) ยท
  2. Layer (or Graphic) ยท 6. Map ยท 7. View (view.ui) ยท 8. Layer (it changes the server query) ยท
  3. Map (map.ground) ยท 10. LayerView (layerView.highlight())

Checkpoint

  1. You add a layer to map.layers while two views are showing that map. How many LayerViews exist?
  2. Why does view.goTo() return a Promise that sometimes rejects?
  3. What is view.stationary and why is it better than watching view.extent?
  4. What does view.padding change?
  5. Where does WebMap fit in relation to Map?
  6. Give one thing that lives on the Layer and one that lives on the LayerView, and say why each belongs where it does.
  1. Two - one per (layer, view) pair. The Layer itself is shared.
  2. It's an animation that can be interrupted by user input or a subsequent goTo. Rejection with an abort error is the normal signal for "superseded."
  3. A boolean that is false during any animation or user drag and true once things settle. extent changes every frame; stationary changes twice per interaction, so it's the right trigger for expensive work.
  4. It insets the view's effective viewport, so center, goTo fitting, popup placement and default widget positioning all account for UI overlays.
  5. WebMap extends Map, adding loading from a portal item. Anywhere a Map is accepted, a WebMap works.
  6. Layer: definitionExpression - it changes what the server returns, so it is a property of the data. LayerView: filter - it changes what this view draws from data already loaded, so two views can differ.

Further reading


Next: Module 06 - Basemaps, Styles and the UI