Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 44 ยท Maps and Geo

Geographic Projections and Paths

Draw maps with d3-geo: GeoJSON basics, projections (Mercator, Equal Earth, Orthographic), d3.geoPath, fitSize, graticules, centroids, circles and distances.

A map is a special kind of chart where positions come from the Earth. Two ideas do all the work in D3: a projection converts longitude and latitude (degrees on a sphere) into x and y pixels on a flat screen, and a path generator turns GeoJSON shapes into SVG path strings using that projection. Everything else (colors, labels, zoom) is the same SVG skills you already know.

GeoJSON in two minutes

GeoJSON is the standard JSON format for geographic shapes. A Feature has a geometry and properties. A geometry has a type and coordinates in [longitude, latitude] order (x first, which surprises people used to "lat, long").

JavaScript
const lake = {
  type: "Feature",
  properties: { name: "Square Lake" },
  geometry: {
    type: "Polygon",
    coordinates: [[[0, 40], [20, 40], [20, 55], [0, 55], [0, 40]]]  // closed ring
  }
};

Types you will meet: Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, plus Feature and FeatureCollection (a list of features). One important D3 detail: polygon rings must follow the right-hand rule on a sphere: exterior rings run clockwise, holes counter-clockwise. D3 treats the inside of a ring as the smaller side only if wound that way; wrongly wound data fills the entire globe. Tools such as geoproject or turf.rewind fix this.

Projections and paths

JavaScript
const projection = d3.geoMercator();
const path = d3.geoPath(projection);

svg.append("path").datum(lake).attr("d", path);

path(feature) returns the SVG path string. projection([lon, lat]) returns [x, y] pixels for a single point; use it to place circles, labels or pins:

JavaScript
const [x, y] = projection([2.35, 48.85]); // Paris

Fit the map to your SVG

New maps start centred at (0, 0) at a default scale, usually off-screen. Rather than guess scale and translate, let D3 compute them from your data:

JavaScript
projection.fitSize([width, height], featureCollection);        // or
projection.fitExtent([[10, 10], [width - 10, height - 10]], featureCollection); // with margins

You can also configure manually: .center([lon, lat]), .scale(k), .translate([x, y]), .rotate([lambda, phi, gamma]), .clipAngle(deg) and .precision(0.1).

The same shapes in four projections

All four panels draw the same longitudes and latitudes. Mercator stretches the north, Equal Earth preserves areas, and the orthographic view looks like a globe (points on the far side are clipped automatically). Pick a projection by what must be right: shape (conformal, such as Mercator, good for navigation), area (equal-area such as Equal Earth or Albers, needed for choropleths) or look (orthographic).

Common projections

Projection Use
geoMercator web maps, local areas; heavily distorts area near the poles
geoEqualEarth a good default for world maps that compare areas
geoNaturalEarth1 pleasant compromise for world maps
geoAlbers, geoAlbersUsa the US (AlbersUsa puts Alaska and Hawaii in insets)
geoConicConformal, geoConicEqualArea mid-latitude regions
geoOrthographic rotating globes
geoEquirectangular simple lon-lat grid
geoStereographic, geoAzimuthalEqualArea polar or centred views

Helpers: graticule, centroid, area, bounds, distance

  • d3.geoGraticule() generates the latitude and longitude grid lines; d3.geoGraticule10() is a ready-made 10-degree grid; {type: "Sphere"} is a valid GeoJSON-like object for the globe outline.
  • path.centroid(feature), path.bounds(feature) and path.area(feature) return values in pixels, handy for labels.
  • d3.geoCentroid(feature), d3.geoBounds(feature) and d3.geoArea(feature) work on the sphere in degrees and steradians (multiply geoArea by the Earth radius squared, 6371 km, for square kilometres).
  • d3.geoDistance(a, b) returns the great-circle angle in radians; multiply by 6371 for kilometres.
  • d3.geoCircle().center([lon, lat]).radius(degrees)() makes a true circle on the sphere (a polygon).
  • d3.geoInterpolate(a, b) returns a function giving points along a great-circle arc. Draw a flight route as a LineString and the projection bends it correctly.
Distance and a great-circle route

The red line is a great circle: the shortest path on the sphere, which looks curved on a flat map. The result is about 9,560 km.

flowchart LR
  G["GeoJSON: lon, lat"] --> P["projection: x, y"]
  P --> PA["d3.geoPath: SVG path string"]
  PA --> S["svg path d attribute"]

Projection places points, the path generator draws shapes.

Common mistakes

  • Swapping latitude and longitude. GeoJSON and D3 use [lon, lat].
  • Not calling fitSize and then wondering why the map is blank or tiny.
  • Wrong winding order, which fills the entire sphere. Use d3.geoPath on a known-good file or rewind the data.
  • Using Mercator for choropleths of areas: Greenland looks as big as Africa. Use an equal-area projection.
  • Projecting an already-projected data set (some files, such as us-atlas "albers" variants, are pre-projected; use geoIdentity() for them).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In GeoJSON coordinates and in d3 projections, which order is used?

    Longitude (the x axis) comes first. Swapping them is a classic bug.
  2. 2. What does d3.geoPath(projection)(feature) return?

    The path generator converts geometry to the path data string you pass to attr('d', path).
  3. 3. Which method scales and centres a projection so a feature fills a box?

    fitSize([w, h], geojson) (or fitExtent for margins) computes scale and translate for you.
  4. 4. Why prefer an equal-area projection for a choropleth?

    Mercator inflates high-latitude regions, which can mislead viewers about how large they are.

Summary

  • GeoJSON uses [longitude, latitude]; polygons should follow the winding rules.
  • A projection maps lon/lat to pixels; d3.geoPath turns shapes into SVG paths.
  • fitSize and fitExtent set scale and translate automatically.
  • Choose projections for shape, area or look; use graticules, centroids, distances and circles for extras.

Next: Choropleth and World Maps