Module 02 - GIS Concepts for Developers
Level 0 · Foundations · 🟢 Beginner · 3 hours · Prereq: Module 01
What you'll build
A geo-primitives.js module: functions that convert between WGS84 and Web Mercator, compute
real ground distance from projected coordinates, and validate geometry. Plus a written CRS
decision for three scenarios.
This is the module that stops you shipping a map with a 30% measurement error.
Why this matters
Developers who skip this module write code that:
- Puts data in the Gulf of Guinea (0, 0)
- Measures a 1 km buffer that is actually 1.4 km on the ground
- Swaps latitude and longitude and can't work out why Denver is in China
- Uses
OBJECTIDas a permanent key and loses their edits when the service is republished
Each of those is a half-day bug. The theory is 90 minutes.
Concepts
1. The vector data model
Everything in a feature service is one shape:
FEATURE = GEOMETRY + ATTRIBUTES
{
geometry: { type: "point", x: -76.481, y: 44.231, spatialReference: { wkid: 4326 } },
attributes: {
OBJECTID: 42,
NAME: "Kingston City Hall",
BUILT: 1844,
HEIGHT_M: 28.5
}
}
In the SDK, a feature is a Graphic. In GeoJSON it's a Feature. In a database it's a row
with a geometry column. Same idea everywhere.
A layer is a set of features that share a schema. Same geometry type, same fields. You cannot mix points and polygons in one feature layer - that constraint comes from the underlying table, not the API.
2. The seven geometry types
| SDK type | Shape | Example |
|---|---|---|
point |
One position | A tree, a sensor, a bus stop |
multipoint |
Many positions, one feature | A set of survey markers recorded together |
polyline |
One or more paths of positions | A road, a river, a pipe |
polygon |
One or more rings of positions | A parcel, a lake, a zone |
extent |
A rectangle (xmin/ymin/xmax/ymax) | A bounding box, a view's viewport |
mesh |
3D triangles with vertices/faces | A building model, a scanned object |
| - | (there is no "circle" type) | Circles are polygons with many vertices |
The JSON forms you will actually type:
// Point
{ type: "point", longitude: -76.481, latitude: 44.231 }
// or in projected coords:
{ type: "point", x: -8514000, y: 5501000, spatialReference: { wkid: 3857 } }
// Polyline - array of PATHS, each path an array of [x, y] (or [x, y, z])
{ type: "polyline",
paths: [[[-76.5, 44.2], [-76.4, 44.25], [-76.3, 44.3]]],
spatialReference: { wkid: 4326 } }
// Polygon - array of RINGS
{ type: "polygon",
rings: [[[-76.5, 44.2], [-76.4, 44.2], [-76.4, 44.3], [-76.5, 44.3], [-76.5, 44.2]]],
spatialReference: { wkid: 4326 } }
Note the triple nesting on paths/rings. It is [ path ][ vertex ][ x|y ]. A
single-part line still needs the outer array. Getting this wrong produces
"Invalid geometry" errors with no line number, and it is the most common Level 2 mistake.
Ring rules (polygons)
- The first and last vertex must be identical. The ring is explicitly closed.
- Winding order carries meaning in Esri JSON: outer rings are clockwise, holes are counter-clockwise. GeoJSON (RFC 7946) uses the opposite convention for exterior rings (counter-clockwise). Conversion libraries handle it; hand-written geometry often doesn't.
- A polygon with multiple outer rings is a multipart polygon - one feature, several disjoint pieces (think Hawaii).
// A square with a square hole
{
type: "polygon",
rings: [
[[0,0], [10,0], [10,10], [0,10], [0,0]], // outer, clockwise in Esri terms
[[3,3], [3,7], [7,7], [7,3], [3,3]] // hole, counter-clockwise
]
}
3. Raster data
The other half of GIS. A grid of cells, each with one or more values.
| Vector | Raster | |
|---|---|---|
| Model | Discrete objects with boundaries | Continuous surface sampled on a grid |
| Good for | Parcels, roads, points of interest | Elevation, temperature, satellite imagery, land cover |
| Storage | Geometry + attributes | 2D array of numbers + a georeferencing transform |
| In this SDK | FeatureLayer, GraphicsLayer |
ImageryLayer, ImageryTileLayer, ElevationLayer |
A raster's georeferencing is six numbers (an affine transform): origin x/y, cell size x/y, and two rotation terms. That is all "where is this image on Earth" means.
Multi-band rasters: satellite imagery has a value per wavelength band. Landsat 8 has 11.
ImageryLayer lets you pick bands and compute indices client-side - NDVI is
(NIR - Red) / (NIR + Red). Module 09 does this.
4. Coordinate reference systems - the actual content of this module
A coordinate is meaningless without a CRS. (-76.481, 44.231) could be degrees, metres, feet,
or a pixel offset.
A CRS answers three questions:
- What shape is the Earth? (the datum - an ellipsoid plus an anchoring)
- How do we flatten it? (the projection, if any)
- What are the units? (degrees, metres, feet)
Geographic CRS - no projection, angular units
WGS84 / EPSG:4326 is the one you must know.
- Units: degrees
- Longitude: −180 to 180, Latitude: −90 to 90
- The CRS of GPS, GeoJSON, and every consumer API
{ wkid: 4326 }
A degree is not a distance. One degree of latitude is ~111 km everywhere. One degree of longitude is 111 km at the equator and 0 km at the pole. Never compute a distance by subtracting degrees.
Projected CRS - flattened, linear units
Web Mercator / EPSG:3857 is the web default.
- Units: metres
- Origin at 0°,0°; valid to ±85.05° latitude
- Conformal (shapes locally correct), area badly distorted
{ wkid: 3857 }
The critical property: Web Mercator's scale factor is 1 / cos(latitude). A "metre" in
3857 coordinates is a real ground metre only at the equator.
| Latitude | Place | 1 projected metre = | Error if you measure naively |
|---|---|---|---|
| 0° | Quito | 1.00 m | 0% |
| 30° | Cairo | 0.87 m | +15% |
| 44.2° | Kingston, ON | 0.72 m | +40% |
| 51.5° | London | 0.62 m | +61% |
| 60° | Oslo | 0.50 m | +100% |
| 78° | Longyearbyen | 0.21 m | +381% |
Read the last column as: "your buffer is this much too big."
This exact bug is documented in this repository.
CLAUDE.mdgotcha #6, and the fix lives inDesignToolbar.jsxassrToM/mToSr. Real production code, real bug.
Local projected CRS - accurate over a region
For measurement, use a CRS designed for your area:
- UTM zones - the world in 60 six-degree strips. Metres, sub-metre accuracy in-zone.
EPSG:326xxnorthern hemisphere,EPSG:327xxsouthern. Kingston ON is UTM 18N = EPSG:32618. - State Plane (US), MTM (Quebec/Ontario), British National Grid (
EPSG:27700), and hundreds of national grids.
Find yours at https://epsg.io/ by searching your city.
The decision rule
Storing / exchanging data? → 4326 (WGS84). Universal, unambiguous.
Displaying a web map? → 3857 (Web Mercator). It's what tiles use.
Measuring distance or area? → Geodesic operators, OR project to a local CRS.
NEVER planar maths in 3857.
Local high-accuracy engineering? → The local UTM / State Plane / national grid.
Practical answer for 95% of this course: store 4326, display 3857, measure geodesically.
5. Coordinate order - the bug that never dies
| System | Order |
|---|---|
| GeoJSON | [longitude, latitude] |
ArcGIS SDK Point |
{ x: longitude, y: latitude } or { longitude, latitude } |
ArcGIS rings/paths |
[longitude, latitude] |
| WKT | POINT(longitude latitude) |
| Leaflet | [latitude, longitude] ← opposite |
| Google Maps | { lat, lng } ← opposite |
| Most GPS device output | latitude first |
| EPSG's formal 4326 axis order | latitude first (!) |
Everything in this course is [lon, lat] / x, y. When you integrate an external API,
check its order before you debug anything else.
The tell: if your data lands in the ocean off West Africa but the shape looks right, you have a null-island problem (missing coordinates). If your data lands in a different continent with the shape rotated or mirrored, you have swapped lat/lon.
6. Scale, generalisation and level of detail
A 1:1000 parcel boundary drawn at 1:1,000,000 is 1,000× more detail than a pixel can show. It costs full tessellation and network payload for nothing.
Two mitigations you will use constantly:
maxAllowableOffset on a query - tells the server to simplify geometry to a tolerance
before sending it.
const query = layer.createQuery();
query.maxAllowableOffset = view.resolution; // simplify to one screen pixel
This routinely cuts payload by 80% with no visible difference.
minScale / maxScale on a layer - don't draw it at all outside a range.
layer.minScale = 100000; // hidden when zoomed out beyond 1:100,000
layer.maxScale = 0; // visible at all closer scales
Note the direction: minScale is the zoomed-out limit and the larger number. This is
backwards from intuition and catches everyone once.
7. Attributes, fields and the OBJECTID
Feature service fields have types that matter:
| Type | Notes |
|---|---|
esriFieldTypeOID |
The primary key. Exactly one per layer. Read layer.objectIdField |
esriFieldTypeGlobalID |
A GUID, stable across republishing. Use this for external references |
esriFieldTypeString |
Has a length. Exceeding it fails the edit |
esriFieldTypeInteger / SmallInteger / Double / Single |
Numeric |
esriFieldTypeDate |
Epoch milliseconds UTC, not a string, not seconds |
Three rules that will save you real time:
- Never hard-code
"OBJECTID". Some services call itFID,ObjectId, oresri_oid. Readlayer.objectIdField. - OBJECTIDs are not stable. Republish the data and they can all change. If you store a
reference in another system, store the
GlobalIDor a business key. - Dates are numbers.
attributes.INSPECTEDis1712345678000. Convert withnew Date(value). If you get 1970, you were handed seconds instead of milliseconds.
Coded value domains - the field stores 2, the domain says 2 = "Commercial".
await layer.load();
const field = layer.fields.find(f => f.name === "LAND_USE");
const domain = field.domain; // CodedValueDomain
const label = domain?.getName(2); // "Commercial"
If your popups show numbers where users expect words, you have an unresolved domain.
Arcade's DomainName() (Module 17) handles this for you.
8. Topology and validity
A geometry can be syntactically fine and geometrically broken:
- Self-intersecting polygon (a bowtie) - area is ambiguous
- Unclosed ring - first ≠ last vertex
- Duplicate consecutive vertices - zero-length segments
- Wrong winding order - a hole read as an outer ring, or vice versa
Symptoms: rendering artefacts, buffers that return nothing, intersects that returns the wrong
answer, and - the classic - an area of 0 or a negative number.
In 5.0 the fix is simplifyOperator:
import * as simplifyOperator from "@arcgis/core/geometry/operators/simplifyOperator.js";
await simplifyOperator.load();
if (!simplifyOperator.isSimple(polygon)) {
polygon = simplifyOperator.execute(polygon);
}
Always simplify user-drawn geometry before analysis. People draw bowties constantly.
Build it - geo-primitives.js
Step 1 - WGS84 ↔ Web Mercator, by hand
// geo-primitives.js
const R = 6378137; // WGS84 semi-major axis, metres
const MAX_LAT = 85.05112877980659; // where Mercator y = ±πR
const rad = (d) => (d * Math.PI) / 180;
const deg = (r) => (r * 180) / Math.PI;
/** WGS84 [lon, lat] degrees → Web Mercator [x, y] metres */
export function lonLatToWebMercator([lon, lat]) {
const clamped = Math.max(-MAX_LAT, Math.min(MAX_LAT, lat));
return [
R * rad(lon),
R * Math.log(Math.tan(Math.PI / 4 + rad(clamped) / 2)),
];
}
/** Web Mercator [x, y] metres → WGS84 [lon, lat] degrees */
export function webMercatorToLonLat([x, y]) {
return [
deg(x / R),
deg(2 * Math.atan(Math.exp(y / R)) - Math.PI / 2),
];
}
What the forward maths does: longitude scales linearly (it is just an angle around the
axis). Latitude goes through ln(tan(π/4 + φ/2)) - the inverse Gudermannian - which is what
stretches the poles to infinity. Hence the clamp at 85.05°.
What the inverse does: 2·atan(e^(y/R)) − π/2 is the Gudermannian function, undoing it.
You saw this exact expression in CLAUDE.md as wmYToLatRad.
You will not normally hand-roll this - the SDK has webMercatorUtils. You are writing it
so the scale factor in the next step is not magic.
Step 2 - The scale factor
/**
* Web Mercator scale distortion at a given latitude.
* Multiply a projected-metre distance by this to get ground metres.
*/
export function mercatorScaleFactor(latitudeDegrees) {
return Math.cos(rad(latitudeDegrees));
}
/** Convert a distance measured in EPSG:3857 units to real ground metres. */
export function projectedToGroundMetres(projectedMetres, atLatitude) {
return projectedMetres * mercatorScaleFactor(atLatitude);
}
/** Convert a desired ground distance into EPSG:3857 units at a latitude. */
export function groundToProjectedMetres(groundMetres, atLatitude) {
return groundMetres / mercatorScaleFactor(atLatitude);
}
This is the fix for the 40% error. If a user asks for a 500 m buffer in Kingston and you
buffer by 500 in 3857 units, you produce a 360 m buffer on the ground. Call
groundToProjectedMetres(500, 44.23) → 698, and buffer by that.
Prove it to yourself:
const [x1, y1] = lonLatToWebMercator([-76.5, 44.23]);
const [x2, y2] = lonLatToWebMercator([-76.4, 44.23]);
const projected = Math.hypot(x2 - x1, y2 - y1);
console.log("projected metres:", Math.round(projected)); // ~11132
console.log("ground metres:", Math.round(projectedToGroundMetres(projected, 44.23))); // ~7975
// Cross-check with haversine from Module 01:
// haversineDistance([-76.5, 44.23], [-76.4, 44.23]) ≈ 7975 ✓
The projected number is 40% too big, exactly as the table predicted.
Step 3 - Geometry validation
/** True if a ring's first and last vertices are identical. */
export function isRingClosed(ring) {
if (!ring || ring.length < 4) return false;
const [fx, fy] = ring[0];
const [lx, ly] = ring[ring.length - 1];
return fx === lx && fy === ly;
}
/** Close a ring if it isn't already. Returns a new array. */
export function closeRing(ring) {
return isRingClosed(ring) ? ring : [...ring, ring[0]];
}
/**
* Signed area via the shoelace formula.
* Negative = clockwise in a standard x-right/y-up frame,
* which is the Esri convention for an OUTER ring.
*/
export function signedArea(ring) {
const r = closeRing(ring);
let sum = 0;
for (let i = 0; i < r.length - 1; i++) {
const [x1, y1] = r[i];
const [x2, y2] = r[i + 1];
sum += x1 * y2 - x2 * y1;
}
return sum / 2;
}
export const isClockwise = (ring) => signedArea(ring) < 0;
What the shoelace formula does: sums the cross products of consecutive vertex pairs. The result is twice the signed area; the sign tells you the winding direction. It is the cheapest way to answer "is this ring an outer ring or a hole."
Where you'll use it: validating imported GeoJSON before converting to Esri JSON. GeoJSON and Esri disagree on winding, and a wrongly-wound outer ring renders as a hole - an invisible polygon that is technically there.
Step 4 - A bbox that survives the antimeridian
/**
* Bounding box of [lon, lat] points.
* Handles the antimeridian by choosing the narrower of the two spans.
*/
export function safeBoundingBox(points) {
if (!points?.length) return null;
const lons = points.map(([lon]) => lon);
const lats = points.map(([, lat]) => lat);
const ymin = Math.min(...lats);
const ymax = Math.max(...lats);
const naiveMin = Math.min(...lons);
const naiveMax = Math.max(...lons);
const naiveSpan = naiveMax - naiveMin;
// Shift negative longitudes into 0..360 and measure again
const shifted = lons.map((l) => (l < 0 ? l + 360 : l));
const shiftedMin = Math.min(...shifted);
const shiftedMax = Math.max(...shifted);
const shiftedSpan = shiftedMax - shiftedMin;
if (shiftedSpan < naiveSpan) {
return {
xmin: shiftedMin > 180 ? shiftedMin - 360 : shiftedMin,
xmax: shiftedMax > 180 ? shiftedMax - 360 : shiftedMax,
ymin, ymax, crossesAntimeridian: true,
};
}
return { xmin: naiveMin, xmax: naiveMax, ymin, ymax, crossesAntimeridian: false };
}
The problem this solves: Fiji spans 180°. Points at 179° and −179° are 2° apart on the
ground, but Math.min/Math.max say the bbox spans 358° - the whole world. Your goTo
zooms out to the entire planet and you spend an hour confused.
How it works: measure the span both ways and keep the narrower one. Not the most rigorous solution but correct for any dataset that doesn't genuinely wrap the globe.
Step 5 - Field type helpers
/** Feature service dates are epoch milliseconds UTC. */
export function toDate(value) {
if (value == null) return null;
// Heuristic: values below ~year 2001 in ms are almost certainly seconds
const ms = value < 1e11 ? value * 1000 : value;
return new Date(ms);
}
/** Resolve a coded-value domain label, falling back to the raw value. */
export function domainLabel(field, value) {
const coded = field?.domain?.codedValues;
if (!coded) return value;
return coded.find((cv) => cv.code === value)?.name ?? value;
}
Why the seconds heuristic: plenty of upstream systems (and every Unix tool) emit seconds. If a date renders as 1970-01-20, you were given seconds. The heuristic isn't rigorous - document it and prefer to fix the source.
How it works
Why there are two "Earth shapes" and it matters
A datum anchors an ellipsoid to the actual planet. WGS84 and NAD83 use nearly identical ellipsoids but different anchorings - and North America drifts about 2.5 cm/year relative to the WGS84 frame.
Practical consequence: NAD83 and WGS84 coordinates for the same point differ by 1-2 metres in North America today. Irrelevant for a city-scale web map. Very relevant for a survey or utility-locate application, where 1.5 m is the difference between the gas main and the fibre.
If your app's accuracy requirement is sub-metre, you need a real datum transformation, and
projectOperator supports one via geographicTransformation.
Why geodesic measurement is the default answer
A geodesic calculation runs on the ellipsoid directly. It never touches a projection, so it cannot inherit a projection's distortion. It is correct at any latitude, over any distance, in any CRS.
The cost is CPU - a geodesic buffer is an iterative solution, not a formula. For hundreds of buffers per frame, project to a local CRS and use planar. For anything else, geodesic.
In 5.0:
import * as geodesicBufferOperator from "@arcgis/core/geometry/operators/geodesicBufferOperator.js";
await geodesicBufferOperator.load();
const buffer = geodesicBufferOperator.execute(point, 500, { unit: "meters" });
Module 25 goes deep. What you need now: planar in 3857 is wrong, and you know why.
Why polygons need explicit rings and holes
The alternative - inferring holes from containment - requires an O(n²) point-in-polygon test for every ring pair, on every render. Explicit winding order makes it O(n) with a shoelace sum.
Once you know that, the "why does my hole render as a solid" bug becomes obvious: you handed the renderer two clockwise rings, and by the convention that means two outer parts.
Common mistakes
Assuming metres because the number looks like metres.
x: -8514000 is Web Mercator. x: 452000 might be UTM. x: -76.4 is degrees. Always check
spatialReference.wkid.
Mixing spatial references in one operation.
Buffering a 4326 point by "500" gives you 500 degrees. The SDK will often project for you,
but only if the geometry has a spatialReference set. Geometry with no CRS is the real bug.
Using OBJECTID as a business key.
It changes. Use GlobalID or a real key from the source system.
Trusting Math.min on longitude across the antimeridian.
See Step 4.
Comparing floating-point coordinates with ===.
-76.48100000000001 !== -76.481. Compare with a tolerance:
Math.abs(a - b) < 1e-9 for degrees, < 0.001 for metres.
Buffering in Web Mercator and calling it metres. The whole point of this module.
Exercises
Exercise 02.1 - The distortion table
Write a script that, for latitudes 0, 15, 30, 45, 60, 75:
- Takes two points 0.1° of longitude apart at that latitude
- Computes the projected distance in Web Mercator
- Computes the true geodesic distance with
haversineDistancefrom Module 01 - Prints both and the percentage error
Confirm the error matches 1/cos(φ) − 1.
Exercise 02.2 - CRS decisions
For each scenario, name a CRS and justify it in one sentence.
- A national open-data portal publishing municipal boundaries for third-party consumption.
- A web app showing 50,000 delivery stops over a country, with a basemap.
- A utility locating app that must place a buried cable within 30 cm.
- A global climate visualisation showing sea-surface temperature bands by area.
- A drone survey of a 2 km² construction site in Kingston, Ontario.
- EPSG:4326. Exchange format, universally understood, no projection assumption imposed on consumers.
- EPSG:3857 for display (it's what the tiles use), 4326 for storage. Any measurement must be geodesic.
- The local grid - for Ontario, MTM zone 9/10 (EPSG:2952 or similar) or UTM 18N (EPSG:32618), with an explicit NAD83(CSRS) datum. WGS84/NAD83 confusion alone exceeds the 30 cm budget.
- An equal-area projection - Mollweide (ESRI:54009) or Eckert IV. Mercator would make polar bands look enormous, which is a false statement about the data.
- UTM 18N (EPSG:32618) or the provincial MTM zone. Metres, sub-centimetre planar accuracy over 2 km, and planar maths is safe at that extent.
Exercise 02.3 - Fix broken geometry
Given these, say what's wrong and fix each:
const a = { type: "polygon", rings: [[[0,0],[10,0],[10,10],[0,10]]] };
const b = { type: "polyline", paths: [[-76.5, 44.2], [-76.4, 44.3]] };
const c = { type: "point", x: 44.231, y: -76.481, spatialReference: { wkid: 4326 } };
const d = { type: "polygon", rings: [[[0,0],[10,10],[10,0],[0,10],[0,0]]] };
const e = { type: "point", longitude: -76.481, latitude: 44.231 };
a - ring not closed. Add [0,0] at the end.
b - one level of nesting missing. paths is an array of paths:
paths: [[[-76.5,44.2],[-76.4,44.3]]].
c - lat/lon swapped. Should be x: -76.481, y: 44.231. As written it is in Somalia.
d - self-intersecting bowtie. The vertex order crosses itself; reorder to
[[0,0],[10,0],[10,10],[0,10],[0,0]], or run simplifyOperator.
e - no spatialReference. It happens to default to 4326 when you use
longitude/latitude, but be explicit: spatialReference: { wkid: 4326 }. Ambiguity here is
the root of most projection bugs.
Exercise 02.4 - Winding order
Take a GeoJSON polygon with a hole from https://geojson.io/, and:
- Compute
signedAreafor each ring - Report which ring GeoJSON considers exterior
- Report what Esri JSON would need
- Write
geoJsonRingsToEsri(rings)that reverses rings as needed
Checkpoint
- What are the three things a CRS specifies?
- Why is a 1 km buffer computed in EPSG:3857 at 60° N wrong, and by how much?
- A polygon renders as solid when you wanted a hole. What's the likely cause?
- What is
attributes.CREATED_DATEwhen the field type isesriFieldTypeDate? - Why should you never store
OBJECTIDin another system as a foreign key? - Which is the zoomed-out limit:
minScaleormaxScale?
- The datum (Earth shape + anchoring), the projection (if any), and the units.
- Web Mercator's scale factor is 1/cos(φ). At 60°, cos = 0.5, so 1000 projected units is only 500 real metres - the buffer is half the size the user asked for (or, buffering by 1000 ground-metres' worth of units, 2× too big, depending which direction you got wrong).
- Both rings have the same winding order, so the renderer treats them as two outer parts rather than an outer and a hole.
- A number - epoch milliseconds UTC. Not a string, not a
Date, not seconds. - OBJECTIDs are assigned by the geodatabase and can be reassigned on republish, append, or
migration. Use
GlobalIDor a business key. minScale. Scale denominators get bigger as you zoom out, so the zoomed-out limit is the larger number and is confusingly named "min".
Further reading
- https://epsg.io/ - look up any CRS; the "bounds" section tells you where it's valid
- https://developers.arcgis.com/documentation/spatial-references/ - Esri's CRS guide
- https://macwright.com/2015/03/23/geojson-second-bite.html - the best short GeoJSON explainer
- https://www.rfc-editor.org/rfc/rfc7946 - the GeoJSON spec, 30 pages and genuinely readable
- https://developers.arcgis.com/javascript/latest/api-reference/esri-geometry-Polygon.html -
the SDK's polygon reference, including
isClockwise
Level 0 complete. Take the L0 challenge, then start Module 03 - Hello Map, the CDN Path.