Module 03 - Hello Map: the CDN Path
Level 1 ยท Your First Maps ยท ๐ข Beginner ยท 2 hours ยท Prereq: Module 02
What you'll build
A complete, working web map in one HTML file with no build step, no npm install, and no
framework. Centred on a location you choose, with a basemap, zoom controls, a scale bar, and a
point marker you place yourself.
Then you will deliberately break it four ways and fix each one, so you own the debugging checklist rather than borrowing it.
Why this matters
Nobody ships production apps from a CDN with no build step - but learning the SDK is much easier without a bundler in the way. When something doesn't work in this module, there are only three possible causes. In a Vite project there are fifteen.
The CDN path is also genuinely the right choice sometimes: a one-page demo, an embedded map in a CMS, a proof of concept for a stakeholder, a CodePen you send to a colleague. Knowing it exists is useful.
Concepts
1. Two distribution channels, one SDK
CDN (js.arcgis.com) |
npm (@arcgis/core) |
|
|---|---|---|
| Setup | One <script type="module"> |
npm install, a bundler |
| Bundle | Whole SDK, served from Esri's CDN, cached globally | Only what you import |
| Offline | No | Yes |
| Version pinning | URL path (/5.0/) |
package.json |
| Tree shaking | No | Yes |
| Right for | Demos, embeds, learning | Everything real |
The API is identical. Code you write here works unchanged in Module 04.
2. The CDN's ES module entry point
<script type="module">
import Map from "https://js.arcgis.com/5.0/@arcgis/core/Map.js";
import MapView from "https://js.arcgis.com/5.0/@arcgis/core/views/MapView.js";
</script>
Note:
type="module"- required. Without it,importis a syntax error.- The URL mirrors the npm path exactly:
@arcgis/core/views/MapView.js. 5.0pins the version. Use it. An unpinned CDN is a production outage waiting for a release.
3. CSS is not optional
<link rel="stylesheet" href="https://js.arcgis.com/5.0/esri/themes/light/main.css" />
The SDK ships its own stylesheet with widget styles, icon fonts and layout rules. Without it the map still draws but every widget is unstyled - a stack of naked buttons. If your app looks broken but the map works, this is the first thing to check.
Themes available: light, dark. Both live at
https://js.arcgis.com/5.0/esri/themes/{theme}/main.css.
4. The container must have a height
This is the single most common beginner failure, so it gets its own section.
html, body, #viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
height: 100% means "100% of my parent's height." If body has no height, #viewDiv's 100%
resolves to zero, and you get a 0-pixel map - which looks exactly like a broken map.
The chain must be unbroken from html down to your div. Alternatives that avoid the chain
entirely:
#viewDiv { height: 100vh; } /* viewport units - no parent dependency */
#viewDiv { position: absolute; inset: 0; } /* fill the positioned ancestor */
Build it
Step 1 - The skeleton
Create index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>Hello Map</title>
<!-- The SDK's stylesheet. Without this, widgets render unstyled. -->
<link rel="stylesheet" href="https://js.arcgis.com/5.0/esri/themes/light/main.css" />
<style>
/* The height chain: html โ body โ #viewDiv. Break any link and the map is 0px tall. */
html, body, #viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
}
</style>
</head>
<body>
<div id="viewDiv"></div>
<script type="module">
// Code goes here in Step 2
</script>
</body>
</html>
What each part does:
<meta name="viewport">withuser-scalable=nostops mobile browsers pinch-zooming the page when the user means to zoom the map.<div id="viewDiv">is the container. The name is conventional, not required.<script type="module">at the end of<body>so the div exists when the script runs.
Open it. You should see a blank white page. That is correct - there is no map yet.
Step 2 - A map and a view
Inside the <script type="module">:
import esriConfig from "https://js.arcgis.com/5.0/@arcgis/core/config.js";
import Map from "https://js.arcgis.com/5.0/@arcgis/core/Map.js";
import MapView from "https://js.arcgis.com/5.0/@arcgis/core/views/MapView.js";
// Your API key from SETUP.md. Restricted by referrer in the developer dashboard.
esriConfig.apiKey = "PASTE_YOUR_API_KEY_HERE";
// 1. The DATA MODEL - what is on the map. No rendering concept at all.
const map = new Map({
basemap: "arcgis/navigation",
});
// 2. The VIEW - how and where it is drawn. Owns the camera, the UI, the events.
const view = new MapView({
container: "viewDiv", // id of the div, or the element itself
map: map, // the data model to display
center: [-76.481, 44.231], // [longitude, latitude] - Kingston, Ontario
zoom: 13, // 0 = whole world, ~20 = building level
});
Line by line:
| Line | What it does |
|---|---|
esriConfig.apiKey = โฆ |
Sets a global key used for every request to Esri-hosted services. Must be set before the first request, which is why it comes first. |
new Map({ basemap }) |
Constructs the data model. "arcgis/navigation" is a basemap style name resolved by the basemap styles service. |
new MapView({ container }) |
Constructs the view and starts rendering into that element. |
center: [lon, lat] |
Longitude first. See Module 02 if that surprises you. |
zoom: 13 |
Roughly neighbourhood scale. |
Change the centre to your own city. Look it up on https://geojson.io/ - click a point and
read the coordinates. Remember: [lon, lat].
Reload. You should have a working, pannable, zoomable map with a zoom control in the top-left.
Step 3 - Wait for the view properly
Add this after the view:
view.when(
() => {
console.log("View is ready.");
console.log("Spatial reference WKID:", view.spatialReference.wkid);
console.log("Extent:", view.extent.toJSON());
},
(error) => {
console.error("View failed to load:", error);
}
);
Why this matters: new MapView() returns immediately. The view is not ready - it hasn't
sized itself, resolved the basemap's spatial reference, or created its extent. Reading
view.extent on the next line gives you null.
view.when() returns a Promise resolving when the view is usable. It is safe to call at any
time, including after the view is already ready.
Note the WKID it logs: 3857. You passed a [lon, lat] centre in degrees, and the SDK
projected it into the basemap's spatial reference. It does this automatically for centre -
it will not do it silently for arbitrary geometry, which is Module 25's business.
Step 4 - Add a point graphic
import Graphic from "https://js.arcgis.com/5.0/@arcgis/core/Graphic.js";
const cityHall = new Graphic({
geometry: {
type: "point",
longitude: -76.4813,
latitude: 44.2312,
},
symbol: {
type: "simple-marker",
style: "circle",
color: [0, 102, 255, 0.9],
size: 14,
outline: { color: "white", width: 2 },
},
attributes: {
name: "Kingston City Hall",
built: 1844,
},
popupTemplate: {
title: "{name}",
content: "Built in {built}.",
},
});
view.graphics.add(cityHall);
What just happened, and the two ideas hiding in it:
Autocasting. You passed plain objects for geometry, symbol and popupTemplate. The SDK
read the type property (or the target property's expected class) and constructed
Point, SimpleMarkerSymbol and PopupTemplate for you. These are equivalent:
// Autocast
symbol: { type: "simple-marker", color: "red", size: 12 }
// Explicit - needs an import
import SimpleMarkerSymbol from "https://js.arcgis.com/5.0/@arcgis/core/symbols/SimpleMarkerSymbol.js";
symbol: new SimpleMarkerSymbol({ color: "red", size: 12 })
Use autocasting. It is idiomatic, it is fewer imports, and it is smaller bundles.
view.graphics vs a GraphicsLayer. view.graphics is a convenience collection that
belongs to the view, not the map. It is fine for a handful of transient markers. Real
client-side data goes in a GraphicsLayer added to the map - that's Module 10.
Click the marker. The popup appears, with {name} and {built} substituted from attributes.
Those braces are field substitution, and they work in popup titles, content and labels.
Step 5 - Add widgets
import ScaleBar from "https://js.arcgis.com/5.0/@arcgis/core/widgets/ScaleBar.js";
import Home from "https://js.arcgis.com/5.0/@arcgis/core/widgets/Home.js";
import BasemapToggle from "https://js.arcgis.com/5.0/@arcgis/core/widgets/BasemapToggle.js";
view.ui.add(
new ScaleBar({ view, unit: "metric" }),
"bottom-left"
);
view.ui.add(new Home({ view }), "top-left");
view.ui.add(
new BasemapToggle({ view, nextBasemap: "arcgis/imagery" }),
"bottom-right"
);
How view.ui works: it is a manager for DOM overlaid on the map, with nine named
positions:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ top-left top-right โ
โ โ
โ manual (absolute-positioned children) โ
โ โ
โ bottom-left bottom-right โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Also top-leading/top-trailing (RTL-aware equivalents of left/right).
Every widget takes view. That is how it subscribes to the view's state. A widget without
a view does nothing.
Step 6 - Respond to a click
view.on("click", (event) => {
const { longitude, latitude } = event.mapPoint;
console.log(`Clicked: ${longitude.toFixed(5)}, ${latitude.toFixed(5)}`);
view.graphics.add(new Graphic({
geometry: event.mapPoint,
symbol: {
type: "simple-marker",
color: [255, 140, 0, 0.8],
size: 10,
outline: { color: "white", width: 1.5 },
},
}));
});
What event.mapPoint is: the click's screen position, unprojected into map coordinates.
The SDK gives it to you in the view's spatial reference (3857 here) but exposes
.longitude and .latitude convenience getters that convert to WGS84 on read.
The event also carries event.x / event.y (screen pixels) and event.button. Screen
coordinates matter for hitTest, which is Module 19.
Step 7 - The complete file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>Hello Map</title>
<link rel="stylesheet" href="https://js.arcgis.com/5.0/esri/themes/light/main.css" />
<style>
html, body, #viewDiv { padding: 0; margin: 0; height: 100%; width: 100%; }
#info {
position: absolute; top: 12px; right: 12px; z-index: 10;
background: #fff; padding: 10px 14px; border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,.2);
font: 13px/1.4 system-ui, sans-serif;
}
</style>
</head>
<body>
<div id="viewDiv"></div>
<div id="info">Click the map to drop a marker.</div>
<script type="module">
import esriConfig from "https://js.arcgis.com/5.0/@arcgis/core/config.js";
import Map from "https://js.arcgis.com/5.0/@arcgis/core/Map.js";
import MapView from "https://js.arcgis.com/5.0/@arcgis/core/views/MapView.js";
import Graphic from "https://js.arcgis.com/5.0/@arcgis/core/Graphic.js";
import ScaleBar from "https://js.arcgis.com/5.0/@arcgis/core/widgets/ScaleBar.js";
import Home from "https://js.arcgis.com/5.0/@arcgis/core/widgets/Home.js";
import BasemapToggle from "https://js.arcgis.com/5.0/@arcgis/core/widgets/BasemapToggle.js";
esriConfig.apiKey = "PASTE_YOUR_API_KEY_HERE";
const map = new Map({ basemap: "arcgis/navigation" });
const view = new MapView({
container: "viewDiv",
map,
center: [-76.481, 44.231],
zoom: 13,
});
view.ui.add(new ScaleBar({ view, unit: "metric" }), "bottom-left");
view.ui.add(new Home({ view }), "top-left");
view.ui.add(new BasemapToggle({ view, nextBasemap: "arcgis/imagery" }), "bottom-right");
view.graphics.add(new Graphic({
geometry: { type: "point", longitude: -76.4813, latitude: 44.2312 },
symbol: {
type: "simple-marker", color: [0, 102, 255, 0.9], size: 14,
outline: { color: "white", width: 2 },
},
attributes: { name: "Kingston City Hall", built: 1844 },
popupTemplate: { title: "{name}", content: "Built in {built}." },
}));
const info = document.getElementById("info");
view.on("click", (event) => {
const { longitude, latitude } = event.mapPoint;
info.textContent = `${longitude.toFixed(5)}, ${latitude.toFixed(5)}`;
view.graphics.add(new Graphic({
geometry: event.mapPoint,
symbol: {
type: "simple-marker", color: [255, 140, 0, 0.85], size: 10,
outline: { color: "white", width: 1.5 },
},
}));
});
view.when(
() => console.log("Ready. WKID:", view.spatialReference.wkid),
(err) => console.error("View failed:", err)
);
</script>
</body>
</html>
Save it as academy/code/vanilla-starter/index.html. You will reuse it.
Break it on purpose
Do all four. Each one produces a symptom you will meet again.
Break 1 - Remove the height
Delete height: 100% from the CSS rule.
Symptom: blank white page. No errors.
Diagnosis: DevTools โ Elements โ select #viewDiv โ check the computed height. It's 0.
Lesson: a 0-height container is silent. It never errors, it just doesn't exist.
Break 2 - Corrupt the API key
Change one character in esriConfig.apiKey.
Symptom: grey map, zoom controls work, nothing renders.
Diagnosis: Network tab โ red 403 on basemaps-api.arcgis.com. Open the response -
it says Invalid token.
Lesson: grey + 403 = credentials. Grey + no requests = height or container.
Break 3 - Remove the CSS link
Delete the <link rel="stylesheet">.
Symptom: the map draws normally, but the zoom buttons are unstyled text, the scale bar is a bare div, and the popup has no layout. Lesson: the SDK's rendering and its widget styling are independent. Widget weirdness is almost always the stylesheet.
Break 4 - Swap the centre coordinates
Change center: [-76.481, 44.231] to center: [44.231, -76.481].
Symptom: the map opens in the Southern Ocean, southwest of Australia.
Lesson: [lon, lat]. You will do this at least three more times during this course. Now
you'll recognise the symptom in five seconds instead of twenty minutes.
Fix all four before moving on.
How it works
What new MapView() actually starts
- Finds the container element and measures it.
- Creates a WebGL context (or WebGL2) on a
<canvas>sized to the container. - Attaches a
ResizeObserverso it re-sizes when the container does. - Resolves the map's basemap - a network request to the basemap styles service if you gave a style name.
- Adopts the basemap's spatial reference as the view's, unless you set one explicitly.
- Projects your
centerinto that spatial reference. - Creates a
LayerViewfor each layer in the map. - Starts the render loop.
view.when() resolves after step 7. That is why view.extent is null before it.
Why the basemap decides the spatial reference
Tiles exist in exactly one projection. If the basemap is Web Mercator, everything drawn on top must be Web Mercator, or nothing lines up. Rather than making you specify it, the view adopts the basemap's.
You can override it (new MapView({ spatialReference: { wkid: 32618 } })), but then your
basemap must have tiles in that projection or it won't display at all. Almost always: leave it
alone.
Why the CDN version pin matters more than it looks
https://js.arcgis.com/latest/ exists. Do not use it. When Esri ships 5.1, your production app
changes behaviour with no deploy on your side, and you find out from a user. Pin, then upgrade
deliberately.
Common mistakes
Setting esriConfig.apiKey after creating the map.
The basemap request may already be in flight. Set it first, before any other SDK line.
Using container: document.getElementById("viewDiv") before the DOM is parsed.
If the <script> is in <head> without defer, the div doesn't exist yet. Put the script at
the end of <body> (as here), or use type="module" - which defers by default.
Forgetting type="module".
Uncaught SyntaxError: Cannot use import statement outside a module. Add it.
Opening the file with file:// and expecting everything to work.
ES modules over file:// are blocked by CORS in most browsers. Use Live Server, npx serve .,
or python -m http.server.
Mixing CDN and npm imports in one file.
You get two copies of the SDK, two esriConfig globals, and instanceof checks that fail
mysteriously. Pick one.
Exercises
Exercise 03.1 - Your city, five ways
Rebuild the file for your own city, and add:
- A marker at your home/office with a popup showing an address
CompassandFullscreenwidgets (look them up in the API reference - practise reading it)- A
Locatewidget that jumps to the user's GPS position - A
Searchwidget in the top-right (it works with just{ view }and your API key)
Exercise 03.2 - The coordinate readout
Replace the click handler with a pointer-move handler that continuously updates the info box
with the cursor's coordinates in both WGS84 degrees and Web Mercator metres.
Hint: event.mapPoint.x / .y are in the view's SR; .longitude / .latitude convert.
Then answer: why does the info box update smoothly on pointer-move but you'd never want to
run a query on that event?
Exercise 03.3 - Two views, one map
Create two divs side by side, and two MapViews sharing one Map instance.
- Verify that a graphic added to
map.layersappears in both - Verify that a graphic added to
viewA.graphicsappears in only view A - Set different
zoomvalues on each
Write two sentences explaining what this proves about the Map/View split. This is the core mental model of the whole SDK.
Exercise 03.4 - Read the docs cold
Without any tutorial, add a Sketch widget that lets the user draw a polygon, using only https://developers.arcgis.com/javascript/latest/api-reference/esri-widgets-Sketch.html.
You need: a GraphicsLayer, the layer passed to the Sketch widget, and the widget added to
view.ui. Everything you need is on that page.
This exercise is more about docs literacy than about Sketch. Time-box it to 30 minutes.
Checkpoint
- What is the difference between
map.layersandview.graphics? - Your map is grey, the zoom buttons work, and the console is clean. What do you check?
- Why does
console.log(view.extent)on the line afternew MapView()printnull? - What does autocasting mean, and what property drives it?
- Where does the view's spatial reference come from if you don't set one?
- Why is
https://js.arcgis.com/latest/a bad idea in production?
map.layersbelongs to the data model and appears in every view of that map;view.graphicsbelongs to one view only and is for transient, view-specific overlays.- The Network tab. A clean console with a grey map means requests are failing (403/404) or not being made at all. Grey + no errors + no requests usually means a 0-height container.
- The view initialises asynchronously - it must size itself and resolve the basemap before it
has an extent. Use
await view.when(). - Passing a plain object where the SDK expects a class instance, and letting the SDK construct
it. Driven by the
typestring ("simple-marker","point") or by the target property's declared type. - From the basemap. Tiles exist in one projection, so the view adopts it.
- Your production app silently changes behaviour when Esri publishes a release, with no deploy on your side and no way to roll back except editing the URL.
Further reading
- https://developers.arcgis.com/javascript/latest/get-started-cdn/ - Esri's CDN guide
- https://developers.arcgis.com/javascript/latest/api-reference/esri-views-MapView.html - read the whole property list once. It's long, but it is the map's control surface.
- https://developers.arcgis.com/javascript/latest/sample-code/intro-graphics/ - the graphics sample, with more symbol types