# Maps

A map lives in any scene of a deck, a docs page or a report, written with the same directives as the
rest of Récit. It is drawn **at build time** as static SVG: the same map on the web, in a slide and
in a PDF, with no tile server, no online geocoder and no request to anyone. The base maps and the
offline place gazetteer ship with `@recit/geo` (Natural Earth, public domain).

```md
---
title: Lorem Ipsum in France
format: docs
lang: en
---

## Lorem ipsum by region

:::map{region=FR level=admin1 caption="Lorem ipsum dolor sit amet" source="Lorem dataset"}
::marker{lat=48.8566 lon=2.3522 label="Lorem"}
::marker{lat=45.764 lon=4.8357 label="Ipsum"}
:::

## The world

::map{region=world projection=equal-earth}
```

## The block

| Element             | Role                                                                                       |
| ------------------- | ------------------------------------------------------------------------------------------ |
| `::map{…}`          | a map on its own line                                                                      |
| `:::map{…}` … `:::` | a map with layers: `::marker`, `::route`, `::area` lines and ` ```geojson ` blocks         |
| `region`            | `world` (the default), an ISO 3166-1 alpha-2 code (`FR`), or an extent `"[w,s,e,n]"`       |
| `level`             | `admin0`, the countries (the default), or `admin1`, the regions of one country             |
| `projection`        | one of the closed list below; chosen from the region when absent                           |
| `insets`            | `none` (the default) or `auto`: stacked boxes for overseas territories (`FR` for now)      |
| `caption`, `source` | the title of the map and where its data comes from, shown under it                         |
| `height`            | the height of the drawing, from 120 to 2000 (the width is 960); from the region by default |
| `::marker{…}`       | a place, by `lat` and `lon` (-90 to 90, -180 to 180) or `place="Name, CC"`, and its label  |

Projections: `equal-earth` (the default for the world), `natural-earth`, `mercator`,
`conic-conformal` (the default for a country, close to Lambert 93 for France), `albers`,
`albers-usa` (the default for the United States, with Alaska and Hawaii), `orthographic` (a globe)
and `azimuthal-equal-area`. Each is centred on its region and fitted to the frame.

A map of a country is framed on its main part: Corsica stays with France, while overseas territories
such as French Guiana and Réunion stay outside the main frame unless `insets=auto` draws them beside
it.

## Every attribute

One table per directive; the rest of the page shows each one at work.

| Directive  | Attribute                        | Values                                                                                             |
| ---------- | -------------------------------- | -------------------------------------------------------------------------------------------------- |
| `::map`    | `region`                         | `world` (default), `FR`, or `"[w,s,e,n]"`                                                          |
| `::map`    | `level`                          | `admin0` (default), `admin1`                                                                       |
| `::map`    | `projection`                     | the closed list above                                                                              |
| `::map`    | `insets`                         | `none` (default), `auto`: five overseas territory boxes beside a map of `FR`                       |
| `::map`    | `caption`                        | the title of the map                                                                               |
| `::map`    | `source`                         | where the data comes from; **mandatory with `data=`**                                              |
| `::map`    | `height`                         | 120 to 2000                                                                                        |
| `::map`    | `data`, `key`, `value`, `scheme` | the choropleth, see below                                                                          |
| `::map`    | `labels`                         | `auto` (default), `short`, `none`: the names of the markers                                        |
| `::map`    | `legend`                         | `below` (default), `side` (default in `square` and `share`): legend, caption and source beside it  |
| `::map`    | `worldview`                      | `IN`, `MA`…: the borders as that country sees them, see below; the de facto borders by default     |
| `::map`    | `tiles`                          | `liberty`, `positron`, `bright` or a style URL ending in `.json`: the interactive map, see the end |
| `::map`    | `attribution`                    | the credit of a style from another site (`tiles=https://…`), mandatory there                       |
| `::marker` | `lat`, `lon`                     | numbers, -90 to 90 and -180 to 180 (not with `place`)                                              |
| `::marker` | `place`                          | `"Lyon"` or `"London, GB"`, resolved offline in the Natural Earth gazetteer (not with `lat`/`lon`) |
| `::marker` | `label`                          | the name of the place, localisable (`place` name by default; `[text]` or `label=` wins)            |
| `::route`  | `from`, `to`                     | a marker label, or `lat,lon`                                                                       |
| `::route`  | `style`                          | `solid` (default), `dashed`, `dotted`                                                              |
| `::route`  | `reveal`                         | `draw`, `fade`, `none`: read by the atlas and the motion blocks                                    |
| `::route`  | `label`                          | a name for the line                                                                                |
| `::area`   | `src`                            | a GeoJSON file beside the story                                                                    |
| `::area`   | `label`, `reveal`                | a name; `draw`, `fade` or `none`                                                                   |

A marker on its own:

```md
:::map{region=FR}
::marker{lat=48.8566 lon=2.3522 label="Lorem"}
:::
```

## Layers

A `:::map` holds its layers, one per line:

````md
:::map{region=FR caption="Lorem to Dolor"}
::marker{lat=48.8566 lon=2.3522 label="Lorem"}
::marker{lat=43.2965 lon=5.3698 label="Dolor"}
::route{from="Lorem" to="Dolor" style=dashed}
::route{from="Lorem" to="45.764,4.8357"}
::area{src="zones/lorem.geojson" label="Lorem zone"}
```geojson
{ "type": "Polygon", "coordinates": [[[2, 46], [3, 46], [3, 47], [2, 47], [2, 46]]] }
```
:::
````

- `::route{from to style label}`: a line along the great circle. `from` and `to` are the labels of
  markers of the same map, or coordinates written `lat,lon`; `style` is `solid` (the default),
  `dashed` or `dotted`. `reveal=draw|fade|none` is kept for the motion blocks and the atlas.
- `::area{src label}`: a GeoJSON file next to the story (never a URL, never outside its folder).
- ` ```geojson `: GeoJSON written in the story. TopoJSON is not read: convert it to GeoJSON first.

GeoJSON is `[longitude, latitude]`, and a polygon may be wound either way: the map winds it the way
d3-geo expects, so a polygon never fills the globe. A route to a label no marker has, a file that
cannot be read or a position off the globe is an error with the line of its layer.

### Placing a marker by name

Instead of `lat=` and `lon=`, a marker can name a populated place with `place=`:

```md
:::map{region=world caption="Offices"}
::marker{place="Lyon"}
::marker{place="London, GB" label="UK office"}
::marker[French hub]{place="Paris, FR"}
:::
```

- **Offline at build time**: `place=` is resolved against `assets/places.json` in `@recit/geo`,
  built from Natural Earth 5.1.2 Populated Places (1:10m, 7,342 places, public domain). No network
  request is ever made.
- **Matching and disambiguation**: lookup ignores case and accents. Without `, CC` (an ISO 3166-1
  alpha-2 country code), it picks the most populous match; if a homonym in another country exceeds a
  tenth of that place's population, build fails with an ambiguity error asking for `, CC`.
- **Default label**: the label defaults to the place's name in the gazetteer; `label=` and bracketed
  `[text]` win over it.
- **No mixing**: `place=` and `lat=`/`lon=` cannot be combined on the same `::marker`.
- **JSON twin**: the JSON twin keeps the directive as written.

### The names of the markers

`labels=auto` (the default) writes each marker's name beside its point, to the right, or to the
left, above or below when it would cross another name, a point or the edge of the map; a name with
no free place is left out of the drawing, and at most 12 names are written. `labels=short` keeps the
first word of each name (or its first 12 characters), and `labels=none` writes none. A name left out
stays in the title of its point and in the table of the map's data.

## A choropleth

A map colours its countries, or the regions of one country, from a source of the story's `data:`
(the same sources as `::chart`). The numbers always come from that source, never from the Markdown:

```md
---
title: Lorem Ipsum Quarterly
data:
  sales: ./data/sales-by-country.csv
---

::map{data=sales key=country value=revenue source="Lorem dataset" caption="Lorem by country"}

::map{region=FR level=admin1 data=departments key=code value=score scheme=diverging source="Lorem"}
```

| Attribute | Role                                                                                                      |
| --------- | --------------------------------------------------------------------------------------------------------- |
| `data`    | the name of a source under `data:`                                                                        |
| `key`     | its column of codes: ISO alpha-2 or alpha-3 for countries (`FR`, `FRA`), ISO 3166-2 (`FR-75`) at `admin1` |
| `value`   | its column of numbers                                                                                     |
| `source`  | **required**: where the numbers come from, shown under the map                                            |
| `scheme`  | `sequential` (the default, light to strong) or `diverging` (two ends around the middle)                   |

The values are cut into at most five classes of equal, round width (`0 to 25`, `25 to 50`…). The
legend writes the bounds of every class, a shape without a value is "No data", each shape says its
value on hover, and the table under the map lists every value, the highest first. Countries join on
`ISO_A3_EH` of Natural Earth, never on the `-99` its `ISO_A3` gives France and Norway.

## Overseas insets

With `insets=auto`, a map of France (`region=FR`) draws Guadeloupe, Martinique, French Guiana,
Réunion and Mayotte in five boxes stacked in a column to the left of the main map, each at its own
scale and with the colour it has on the map (including its choropleth shade). By default
(`insets=none`, or omitted), no inset is drawn and the map keeps its usual frame.

```md
:::map{region=FR level=admin1 insets=auto data=departments key=code value=score source="Lorem dataset" caption="Lorem across France"}
::marker{lat=48.8566 lon=2.3522 label="Lorem"}
::marker{lat=-20.8823 lon=55.4504 label="Ipsum"}
:::
```

A `::marker` inside one of those five territories is drawn in its box, and its label stays inside
that box: a label too long for it is left out, and the name stays in the dot's tooltip. The labels
of the main map never reach into the column of boxes. Only France (`region=FR`) has insets for now:
elsewhere, `insets=auto` emits a warning and draws the map without insets. Routes (`::route`) and
areas (`::area`, ` ```geojson `) stay on the main map.

In a film, a `::map` with `insets=auto` keeps the same column: the five boxes stay still while the
camera moves the main map beside them, a marker of a territory is drawn in its box, and a choropleth
shade appears in a box with its class. An `atlas` asks for them with its `insets: auto` setting:
when one of its views shows France (`camera=FR`), the column stays beside every view; an atlas that
never shows `FR` draws none and warns.

## Disputed borders

Natural Earth draws the borders **de facto**: the line that is held on the ground. Where two
countries claim the same land, `worldview=` draws the map as one of them sees it:

```md
::map{region=MA worldview=MA}
```

The value is the ISO 3166-1 alpha-2 code of one of the 31 points of view of Natural Earth 5.1.2:
`AR`, `BD`, `BR`, `CN`, `DE`, `EG`, `ES`, `FR`, `GB`, `GR`, `ID`, `IL`, `IN`, `IT`, `JP`, `KR`,
`MA`, `NL`, `NP`, `PK`, `PL`, `PS`, `PT`, `RU`, `SA`, `SE`, `TR`, `TW`, `UA`, `US`, `VN`. Any other
code is an error with its line. The points of view come from the 1:10m layers of Natural Earth,
simplified like the other base maps: the border of a neighbour that is not disputed may differ from
the default map by a stroke.

## Errors with their line

A map never guesses. `recit dev` and `recit build` report, with the file and the line:

- an unknown region or projection, with the likeliest one
  (`::map: region "FX" unknown (did you mean "FR"?)`);
- an unknown attribute (`regoin`), a latitude or a longitude out of bounds, an extent that is not
  four numbers, `level=admin1` without a country;
- an unknown `place=`, an ambiguous `place=` without `, CC` when a homonym in another country
  exceeds one tenth of the largest match's population, or `place=` mixed with `lat=` or `lon=`;
- anything other than `::marker`, `::route`, `::area` or a ` ```geojson ` fence inside a `:::map`.

- a choropleth without `source=`, a `value=`, `key=` or `scheme=` without `data=` (no number is ever
  written inline), an unknown source or column, a `value` column that is not numbers, a key given
  twice, a source where no key matches the map.

A marker outside its region is a **warning**: its latitude and longitude are probably swapped
(`::marker "Lorem": lat=2.3522 lon=48.8566 is outside FR (did you swap lat and lon?)`). So is a key
of the data that matches no country or region
(`2 keys of sales match no country of the map: "-99", "ZZ"`).

`::map` draws countries, regions and choropleths. `mode=points` and `mode=route` are errors that
name the block drawing them: a map of points from data is `::chart{type=points}` (see
[Data directives](/formats/report/data)), where `value=` sizes each point as an area, which makes a
map of proportional circles; a few places are `::marker` in a `:::map`; a route is `::route` in a
`:::map`, and lines from data are a GeoJSON file of lines, `lines=` on `::chart{type=points}`. A
` ```geojson ` fence outside a `:::map` stays a code block, shown as code. Cartograms and density
heat maps are not drawn. `mode=tiles` without `tiles=`, `tiles=` with `data=`, and a style of
another site without `attribution=` are errors with their line.

## What the reader gets

Every map is a `<figure>`: an SVG image (`role="img"`) named by its caption and described by a text
generated from the map (its region, its level, its places), a legend (a square for the region, a dot
for a place: the colour never carries the meaning alone), the caption with its source and the credit
« Made with Natural Earth », and a `<details>` holding the table of the places or regions. The
colours come from the theme tokens, in one hue, so a map reads the same in light and in dark mode,
and prints.

Country names follow the story's language (`Intl.DisplayNames`), numbers too (`Intl.NumberFormat`),
and the language never decides a border: the base maps follow Natural Earth's de facto boundaries.

### Right-to-left languages and social formats

- **Right-to-left (`ar`, `he`, `fa`, `ur`…)**: when `textDirection(locale)` is `"rtl"`, `renderMap`
  sets `lang` and `dir="rtl"` on the outer `<figure>` (leaving left-to-right HTML untouched), so the
  legend, the caption, the source credit and the `<details>` data table flow right-to-left. The
  `<svg>` itself keeps `direction: ltr`: geographic coordinates never mirror (north stays up, west
  stays left), and marker `<text>` labels keep their `start` anchor to the right of the dot.
- **Output layout (`layout`)**: `renderMap` and `geoDirectives` accept `layout` (`ChartLayout`):
  `960` SVG units wide on `page`, `slide` and `poster`, and the card's own `frameSize(layout).width`
  (`360` for a 1080 px export) on `story`, `portrait`, `square` and `share` (passed automatically by
  `@recit/webstory` from the story's aspect ratio), so marker names stay legible on a phone without
  CSS zoom.
- **Side legend (`legend=side`)**: without `legend=`, a map in `layout=square` or `layout=share`
  puts the legend on the side; the other layouts stack the legend, caption and source underneath,
  and `legend=below` puts them back underneath anywhere. `legend=side` sets `data-legend="side"` on
  the figure, draws the map at 62 % of the format's width (`SIDE_LEGEND_SHARE`) with its height
  scaled proportionally, and places the legend, caption and source at the top of a right column
  while keeping the "Data" disclosure across the full width underneath (falling back to a single
  column below `20rem`). The same rule applies to `::chart{type=choropleth|points}`:

  ```md
  ::map{region=FR level=admin1 data=departments key=code value=score legend=side source="Lorem"}

  ::chart{data=regions type=choropleth base=./maps/regions.geojson key=code x=code y=visitors layout=square source="Lorem"}
  ```

## In JSON

In a story's JSON twin the map stays a directive in the scene's `body` (including
`::marker{place=…}`, kept as written). Its typed form is `MapBlockSchema` of `@recit/core/schema`,
published as [`map-block.json`](https://recit.dev/schema/v1/map-block.json):

```json
{
  "type": "map",
  "region": "FR",
  "level": "admin1",
  "caption": { "en": "Lorem ipsum", "fr": "Lorem ipsum (fr)" },
  "layers": [{ "type": "marker", "lat": 48.8566, "lon": 2.3522, "label": "Lorem" }]
}
```

Coordinates, regions, codes and projections are never translated; `caption` and `label` are. Each
entry in `layers` has `type` set to `"marker"` (`lat` and `lon`: a `place=` of the Markdown is
resolved before the block is built), `"route"`, `"area"` or `"geojson"`: a fenced ` ```geojson `
block inside `:::map` becomes `{ "type": "geojson", "data": { … } }` (with an optional localized
`label`), where `layers.data` holds the parsed GeoJSON object.

## In code

`@recit/geo` draws the same map outside a story:

```tsx
import { GeoMap } from "@recit/geo";
import { loadGeoAssets } from "@recit/geo/node";
import "@recit/geo/styles.css";

<GeoMap id="offices" assets={loadGeoAssets()} block={{ region: "FR", level: "admin1" }} />;
```

`geoDirectives(loadGeoAssets())` of `@recit/geo/directives` is the `directives` option of
`compileStory`, what the CLI and `@recit/site-stories` pass. A choropleth reads the loaded sources
of the story: `geoDirectives(loadGeoAssets(), { tables })`, with the `tables` of `loadDataSources`
(`@recit/data/node`); `<GeoMap tables={tables} />` takes them too. `@recit/geo` also exports the
offline gazetteer (`findPlace`, `gazetteerOf`, and the `GazetteerPlace`, `PlaceRow` and `Gazetteer`
types).

## An interactive map, as an option

In Markdown, `tiles=` asks for it:

```md
:::map{region=FR tiles=positron caption="Lorem ipsum"}
::marker[Lorem]{place="Lyon, FR"}
:::
```

`tiles=` names an OpenFreeMap style (`liberty`, `positron`, `bright`), a style served with the site
(`tiles=/maps/style.json`, its `pmtiles://` archives read without a third party), or a style of
another site (`tiles=https://…/style.json`, with `attribution="…"`). A path of the site never starts
with `//` or `/\`: the browser reads both as another host, so they are refused. The static SVG is
drawn as before; its `<figure>` carries the source, the box of the region and the markers in a
`data-recit-tiles` attribute (`TILES_ATTRIBUTE`, `MapTilesData` of `@recit/geo/tiles`), which the
island of a web page reads. A film, a social image or a PDF shows the static map, with a warning.

In the browser, `enhanceTileMaps` of `@recit/geo/tiles` is that island: it puts each such figure
inside a `TileMap`, the static figure as its fallback, and watches for the maps of the next pages.
Without WebGL 2 it moves nothing. It returns its cleanup. A Récit site does it on its own: when a
story holds a `::map{tiles=…}` and the site installs `maplibre-gl` next to `@recit/geo`, its pages
load the island and MapLibre's worker after hydration; without `maplibre-gl`, the maps stay static.
The example `map-tiles` is such a story, read on the maps site under `/maps/tiles`.

```ts
import { enhanceTileMaps } from "@recit/geo/tiles";

const stop = enhanceTileMaps(document, { workerUrl: "/maplibre-gl-worker.mjs" });
```

The map stays a static SVG drawn at build time, with no network: that is what prints, exports and
plays in a film. On a web page, `@recit/geo/tiles` can upgrade it to a sliding map drawn by
[MapLibre GL JS](https://maplibre.org) once the page runs in a browser with WebGL 2. MapLibre and
`pmtiles` are optional peers, loaded by `import()` when the map mounts: a page without an
interactive map never downloads them.

```bash
pnpm add maplibre-gl pmtiles
```

```tsx
import { GeoMap } from "@recit/geo";
import { TileMap } from "@recit/geo/tiles";
import "@recit/geo/styles.css";

<TileMap
  source={{ kind: "openfreemap", style: "positron" }}
  markers={[{ lon: 2.3522, lat: 48.8566, label: "Lorem" }]}
  label="Our offices"
  workerUrl="/maplibre-gl-worker.mjs"
  fallback={<GeoMap id="offices" assets={assets} block={block} />}
/>;
```

- **`fallback`** is the static map. It shows on the server, in print, without WebGL and while
  MapLibre loads, and stays when MapLibre is missing or the style does not load.
- **`source`** has no default, because tiles from a third party send the reader's IP to its host:
  `openfreemap` (the public instance, styles `liberty`, `positron` and `bright`, no key), `pmtiles`
  (a style served with the site whose sources are `pmtiles://` archives, so no third party sees the
  reader), or `style` (any MapLibre style, by URL or inline, with its `attribution`).
- **The attribution** of the tiles is always written under the map (« OpenFreeMap © OpenMapTiles
  Data from OpenStreetMap », or « © OpenStreetMap contributors » for PMTiles).
- **`camera`** is `{ center: [lon, lat], zoom }` or `{ bounds: [[west, south], [east, north]] }`;
  without it the map fits its markers. An inverted latitude and longitude is refused with the
  values.
- **`workerUrl`** is where the site serves `maplibre-gl/dist/maplibre-gl-worker.mjs`: MapLibre finds
  its worker next to its own module, which a bundler moves.
- Scrolling never zooms, so the page keeps its scroll. Dragging, a double click, the arrow keys, `+`
  and `-` and the two zoom buttons move the map, whose canvas is a named region.
