# 3D maps | Rijwind docs

# 3D maps (preview)

`createMap()` from `@rijwind/sdk/gl` draws your map as a **lit 3D world**:
terrain you can tilt into, 3D buildings (with real roof shapes in the
Netherlands and Germany), trees, and sun-lit shading with shadows. It uses the same hosted
styles, the same API key and the same billing as the standard map.

It needs a browser with **WebGPU**. Where that isn't available, or when your
options ask for something the 3D map can't draw yet, `createMap()` quietly
gives you the standard map instead — same options, same camera. Code that
uses the shared MapLibre API runs on either map without branching (see
[Your MapLibre code](#your-maplibre-code)).

> **Preview.** The 3D map is new. The API below is stable enough to build on,
> but expect more MapLibre features to arrive over the coming releases (see
> [Not available yet](#not-available-yet)).

## Quickstart

```sh
npm install @rijwind/sdk
```

```ts
import { createMap } from "@rijwind/sdk/gl";
import { MapStyle, config } from "@rijwind/sdk";
import "@rijwind/sdk/style.css"; // used when the standard map is picked

config.apiKey = "rw_live_•••YOUR_KEY•••";

const { renderer, map } = await createMap({
  container: "map",
  style: MapStyle.STREETS,
  center: [4.8926, 52.3731], // Amsterdam
  zoom: 16,
  pitch: 60,
});

console.log(renderer); // "rijwind-gl" (3D map) or "maplibre" (standard map)
```

`createMap()` is `async`: it resolves once the map exists, before the first
view is drawn. Listen for `load` as usual if you need to wait for that.

Coming from the standard map? Swap the constructor and keep the rest:

```ts
// before
const map = new Map(options);

// after
const { map } = await createMap(options);
```

## Which map you get

`createMap()` returns `{ renderer, map }`:

| `renderer` | `map` is | When |
| --- | --- | --- |
| `"rijwind-gl"` | the 3D map | The browser has WebGPU and every option is one the 3D map draws. |
| `"maplibre"` | the standard [`Map`](/basemap) from `@rijwind/sdk` | Everything else — see the list below. |

You get the **standard map** when:

- the browser has no WebGPU, or the 3D map fails to start;
- `style` is your own style URL or style object (only the hosted
  [`MapStyle`](/styles) values have a 3D version);
- you pass a MapLibre option the 3D map doesn't honour yet: `hash`,
  `maxBounds`, `minPitch` / `maxPitch`, `transformRequest`, or a `projection`
  other than mercator;
- you pass `engine: "maplibre"`.

### Choosing explicitly

```ts
await createMap({ ...options, engine: "auto" });       // default
await createMap({ ...options, engine: "maplibre" });   // always the standard map
await createMap({ ...options, engine: "rijwind-gl" }); // the 3D map, or throw
```

With `engine: "rijwind-gl"` the promise rejects (with the reason) instead of
falling back — useful in a test or a page that only makes sense in 3D. It
also turns off the [late fallback](#late-fallback): if the 3D map later loses
the GPU for good, it fires an `error` event with `fatal: true` and stops
drawing; no standard map replaces it and `onFallback` isn't called.

### Late fallback

In rare cases the browser takes the graphics device away from the page for
good after the map was shown (a driver crash, for instance). With the default
`engine: "auto"`, the 3D map then removes itself and a standard map takes its place in the same container, at
the same camera. `onFallback` hands you the new map so you can re-attach your
sources, layers and listeners:

```ts
const { map } = await createMap({
  ...options,
  onFallback(standardMap, reason) {
    console.warn("Switched to the standard map:", reason);
    addMyLayers(standardMap);
  },
});
addMyLayers(map);
```

When the GPU is lost only briefly, the 3D map recovers on its own and fires
a `recover` event when it's back.

## Browser support

The 3D map runs in browsers with WebGPU — today that's current **Chrome** and
**Edge** (desktop and Android) and **Safari 26** and later (macOS, iOS,
iPadOS), plus Firefox where WebGPU is enabled. Every other browser gets the
standard map, which supports everything the 3D map does and more.

The 3D map ships inside the `@rijwind/sdk` package, so your site runs exactly
the version your lockfile installed — nothing is downloaded as code at
runtime. Your bundler puts it in its own chunk (about 2 MB compressed) that is
loaded only when `createMap()` is called in a browser that can run it, then
cached. Browsers that get the standard map don't load it at all. Updates come
with SDK releases, like any other dependency.

### Content Security Policy

If your site sends a CSP header, allow the 3D map's WebAssembly and workers,
and the map data:

```
script-src  'self' 'wasm-unsafe-eval';
worker-src  blob:;
connect-src 'self' https://cdn.rijwind.com https://api.rijwind.com;
```

Without them the 3D map can't start and `createMap()` falls back to the
standard map.

## Options

`createMap()` takes the same options as the standard [`Map`](/basemap), plus
three of its own:

| Option | Default | |
| --- | --- | --- |
| `engine` | `"auto"` | `"auto"`, `"maplibre"` or `"rijwind-gl"` — see [Choosing explicitly](#choosing-explicitly). |
| `onFallback` | — | `(map, reason) => void`, called on a [late fallback](#late-fallback) (not with `engine: "rijwind-gl"`). |
| `engineUrl` | — | Load the 3D map from a URL you host instead of the copy in the package. Advanced; that copy isn't checked against your lockfile. Leave it unset. |

On the 3D map these options are honoured:

- **Rijwind:** `apiKey`, `style` (a `MapStyle`), `language`, `buildings`
  (`false` hides 3D buildings and trees).
- **Camera:** `center`, `zoom`, `bearing`, `pitch`, `bounds` +
  `fitBoundsOptions`, `minZoom` / `maxZoom`.
- **Gestures:** `interactive`, `dragPan`, `scrollZoom`, `dragRotate`,
  `pitchWithRotate`, `touchZoomRotate`, `touchPitch`, `doubleClickZoom`,
  `cooperativeGestures`.
- **UI:** `attributionControl` (shown by default; `false`, or
  `{ compact, customAttribution }`), `locale`.
- **Text:** `localIdeographFontFamily` — the font family Chinese, Japanese and
  Korean characters are drawn in, from the visitor's device (default
  `"sans-serif"`), as on the standard map.

Standard-map options that are about the flat map's own layers — `terrain`,
`contours` — don't apply: relief is part of the 3D look, and the Outdoor
style brings its contour lines with it.

## Styles

Every hosted style has a 3D version: `STREETS` (= `LIGHT`), `DARK`,
`GRAYSCALE`, `WHITE`, `BLACK`, `OUTDOOR`, `SATELLITE` and `HYBRID` — see
[Styles & tilesets](/styles). Pass them as `style` exactly as you would to
`new Map()`.

To switch at runtime, the 3D map takes the style's **name**:

```ts
if (renderer === "rijwind-gl") {
  await map.setStyle("dark"); // streets · dark · grayscale · white · black · outdoor · satellite · hybrid
}
```

Within the Streets family (and between Satellite and Hybrid) the switch is
usually instant — Dark arrives as nightfall over the same map. Across
families a new map is cross-faded in at the same camera. `map.getStyle().name`
tells you which style is shown.

`setStyle` works as MapLibre's: the new style replaces the whole style, so the
sources, layers, images and feature state you added — and any changes you
made to the basemap's own layers — are gone afterwards. `style.load` fires
again, so add your layers in a `style.load` listener and they come back after
every switch (see the [example](#your-maplibre-code)). `load` fires only once
per map. Event listeners, markers, popups and controls stay, and the map stays
in the same map session.

## Label language

Labels are in **English** by default (`The Hague`, `Brussels`, `Cologne`);
places without an English name keep their local one. This is the same on the
3D map and the standard map. Pass `language` for another language (same local
fallback), or `"local"` for the names used on the ground (`Den Haag`,
`Bruxelles`, `Köln`) — on either map:

```ts
const { map } = await createMap({ container: "map", language: "local" });
```

`config.language` sets the default for every map. The codes are the same as
on the [standard map](/basemap#label-language).

**Every script is drawn.** Greek, Cyrillic, Vietnamese, Thai, Armenian and
Georgian names; Chinese, Japanese and Korean (from the device's fonts, so
nothing extra is downloaded for them); Hindi, Marathi and Nepali. Arabic,
Persian, Urdu and Hebrew are joined and laid out right to left by the 3D map
itself — no RTL plugin to load — so with `language: "local"` it shows
القاهرة and תל אביב, where the standard map shows `Cairo` and `Tel Aviv`
unless you load MapLibre's RTL text plugin. Names in scripts that need more
than that (Bengali, Khmer, Burmese, …) are shown in English, as on the
standard map. Fonts for a script are fetched when a label on screen needs
them: a map of Amsterdam downloads none of this. To change the language at
runtime, call `setLanguage` — on either map (since SDK 0.5.0):

```ts
map.setLanguage("de"); // or "local", "en", …
```

On the 3D map this redraws the map in the new language, which — like any
`setStyle` — means your own layers are added again from `style.load`.

## Your MapLibre code

The 3D map has MapLibre's runtime API with MapLibre's names, so code written
for MapLibre GL JS (or the standard `Map`) runs on it unchanged. That covers:

- **Sources and layers:** GeoJSON sources (inline data or a URL, `setData`,
  `generateId`, clustering with `cluster` / `clusterRadius` /
  `clusterMaxZoom` / `clusterProperties` and `getClusterExpansionZoom`,
  `getClusterChildren`, `getClusterLeaves`); `addLayer` with
  `fill`, `line` (including `line-dasharray`), `circle`, `symbol` (text and
  icons, `text-variable-anchor`, `symbol-placement: "line"`) and
  `fill-extrusion` layers, and `beforeId` to slot a layer under the labels;
  `removeLayer`, `moveLayer`, `setPaintProperty`, `setLayoutProperty`
  (including `visibility`), `setFilter`, `setLayerZoomRange`.
- **The basemap's own layers:** find them in `map.getStyle().layers`, then
  hide, filter or restyle them by id, or listen to clicks on them.
- **Images:** `addImage`, `loadImage`, `hasImage`, `listImages`,
  `updateImage`, `removeImage` for your own `icon-image` pictures. As in
  MapLibre, `hasImage` / `listImages` include the style's own icons, and
  `addImage` under a name that already exists is an error — use names of
  your own.
- **Interaction:** `setFeatureState` / `getFeatureState` /
  `removeFeatureState` (hover highlights), `queryRenderedFeatures` (at a
  point, in a box, or by `layers` + `filter`), `project` / `unproject`.
- **Camera:** `jumpTo`, `easeTo`, `flyTo`, `fitBounds`, `cameraForBounds`,
  `panTo`, `zoomTo`, `zoomIn` / `zoomOut`, `rotateTo`, `resetNorth`,
  `getCenter`, `getZoom`, `getBounds`, `setPadding`, `resize`, …
- **Handlers:** `map.dragRotate.disable()`,
  `map.touchZoomRotate.disableRotation()`, and the other gesture handlers.
- **Controls:** `addControl` / `removeControl` — your own controls and
  maplibre-gl's `NavigationControl`, `GeolocateControl` and
  `FullscreenControl`.
- **Markers and popups:** `new map.Marker()` and `new map.Popup()` take
  MapLibre's options and methods (`setLngLat`, `setPopup`, `setDraggable`,
  drag events, …) and work on both maps: the 3D map's own, or maplibre-gl's
  on the standard map. maplibre-gl's own `Popup` class works on the 3D map
  too; its `Marker` class doesn't (see [Differences](#differences-to-keep-in-mind)).
- **Lifecycle:** `load` (once), `style.load` (at start and after every
  `setStyle`), `idle`, `isStyleLoaded()`, `loaded()`, `getCanvas()`,
  `remove()`.

This runs unchanged on whichever map you got:

```ts
import { createMap, type MapLibreCompatibleMap } from "@rijwind/sdk/gl";

const created = await createMap({ container: "map", center: [4.9, 52.37], zoom: 12 });
const map: MapLibreCompatibleMap = created.map; // in JavaScript: const { map } = created;

// Fires at start and again after every setStyle, which drops your layers.
map.on("style.load", () => {
  map.addSource("stops", { type: "geojson", data: "/stops.geojson" });
  map.addLayer({
    id: "stops",
    type: "circle",
    source: "stops",
    paint: { "circle-radius": 6, "circle-color": "#2a4fef" },
  });
});

map.on("click", "stops", (e) => {
  new map.Popup()
    .setLngLat(e.lngLat)
    .setText(String(e.features?.[0]?.properties?.name ?? ""))
    .addTo(map);
});
```

**TypeScript:** `createMap()` returns `map` as a union of the two map types,
and TypeScript can't call overloaded methods such as `on` on a union. Typing
it as `MapLibreCompatibleMap` — the MapLibre API both maps share — lets you
write the code once, as above. It includes `setStyle(MapStyle.X)`,
`setLanguage`, `setBuildings` and `enableTraffic` / `disableTraffic`. For what
only one map has (`setStyle("dark")` by name or `setOption` on the 3D map,
`setTerrain3D` or WebGL custom layers on the standard map), narrow on
`renderer` first. In plain
JavaScript none of this applies.

### Events

Map events: `click`, `dblclick`, `contextmenu`, `mousedown`, `mouseup`,
`mousemove`, `mouseout`, `dragstart`, `drag`, `dragend`, `movestart`, `move`,
`moveend`, `zoom`, `rotate`, `pitch`, `idle`, `load`, `style.load`,
`styledata`, `sourcedata`, `data`, `error`, `remove`. Layer events
(`map.on(type, layerId, fn)`): `click`, `dblclick`, `contextmenu`,
`mousedown`, `mouseup`, `mousemove`, `mouseenter`, `mouseleave`, with
`e.features`. Events carry `point`, `lngLat` (on the ground, terrain
included) and `originalEvent`, as in MapLibre.

The 3D map adds `recover` (back after a GPU hiccup) and `interact` (the user
touched the map — handy for stopping an animation).

### Differences to keep in mind

- **Use `map.Marker`.** maplibre-gl's own `Marker` class and `ScaleControl`
  don't work on the 3D map; `new map.Marker()` is the drop-in replacement and
  works on both maps.
- **`setStyle` takes a hosted style:** a `MapStyle` (`MapStyle.DARK`) or its
  name (`"dark"`), not your own style URL or object.
- **`setTerrain3D` is the standard map's.** The 3D map always draws the
  terrain in 3D. `setLanguage` and `setBuildings` work on both maps;
  `setBuildings(false)` also hides the 3D map's trees, and the `color` option
  is the standard map's only (the 3D map draws the buildings' own colours).
- **Custom layers draw with WebGPU,** not WebGL: a MapLibre
  `CustomLayerInterface` written for WebGL won't draw. On the 3D map,
  `render(pass, args)` receives a WebGPU render pass. Weather layers have a
  ready-made WebGPU version — see [Weather layers](#weather-layers).
- **Your layers keep their colours.** Lines and fills you add are drawn in the
  colours you give them on every style, the dark ones included.
- **Fonts.** Text in a font Rijwind doesn't host (a symbol layer without
  `text-font`, for example) is drawn in the basemap's regular font.
- **One world.** Zoomed all the way out, the world is drawn once (no
  repeated copies side by side).
- **Async camera methods.** `flyTo`, `easeTo`, `fitBounds` and friends return
  a promise that resolves when the camera arrives (`moveend` fires too).
  `await map.loaded` resolves after the first view is drawn; `map.loaded()`
  answers like MapLibre's.

## Weather layers

[Vane](https://github.com/Rijwind/vane) weather layers — temperature,
precipitation radar, wind particles and arrows, isolines, value grids — work on
both maps. `@rijwind/sdk/weather` hands you the right layer classes for the map
you got: WebGPU layers on the 3D map, Vane's own on the standard map. The
options and methods are the same either way.

```bash
npm install @rijwind/vane
```

```ts
import { MapStyle } from "@rijwind/sdk";
import { createMap } from "@rijwind/sdk/gl";
import { weatherLayers } from "@rijwind/sdk/weather";
import { VaneDataset, TEMPERATURE_STOPS, TEMPERATURE_CLIM } from "@rijwind/vane";

const created = await createMap({ container: "map", style: MapStyle.DARK, center: [5.3, 52.2], zoom: 6 });
const W = await weatherLayers(created);
const dataset = await VaneDataset.openLatest("https://…/knmi_harmonie_nl_latest.json");

// A coloured surface, sliding between forecast steps
const temperature = new W.ColormapLayer({
  id: "temperature", dataset, variable: "temperature",
  colormap: TEMPERATURE_STOPS, clim: TEMPERATURE_CLIM, opacity: 0.7,
});
created.map.addLayer(temperature);
temperature.setTimestep(3.5); // halfway between step 3 and 4

// Wind, as moving particles or as arrows
created.map.addLayer(new W.ParticlesLayer({ id: "wind", dataset }));
created.map.addLayer(new W.ArrowsLayer({ id: "wind-arrows", dataset }));

// Isolines and numbers on the grid are ordinary map layers
new W.ContoursLayer({ id: "pressure", dataset, variable: "pressure_msl" }).addTo(created.map);
new W.ValuesLayer({ id: "values", dataset, variable: "temperature" }).addTo(created.map);
```

Hide and show a layer with
`map.setLayoutProperty(id, "visibility", "none" | "visible")`; a hidden particle
layer stops animating, so the map can rest. On the 3D map the weather layers sit
on the ground under the labels, follow pitch and bearing, and are anti-aliased
with the rest of the frame. Areas without data stay open.

## Not available yet

These MapLibre features aren't on the 3D map yet. If you need one, pass
`engine: "maplibre"` and you get the standard map, which has them all.

| Feature | What happens on the 3D map |
| --- | --- |
| Tile URL templates (`tiles: [...]`) in raster, vector and raster-dem sources | Not drawn; you get an error or a console warning naming the source. |
| TileJSON `url` sources (raster, vector, raster-dem) | Accepted without an error, but nothing is drawn. |
| `image` sources, `heatmap` layers, `line-gradient`, `fill-pattern` | Not drawn; you get an error or a console warning naming them. |
| Box zoom (shift-drag) and keyboard navigation | Nothing happens; the switches are there but do nothing. |
| `querySourceFeatures`, `getProjection` | Throws, with a message pointing to `engine: "maplibre"`. |
| `setTerrain`, `setSky`, `setLight`, `setProjection` | Ignored, with one console warning — the 3D map has its own terrain, sky and light. |
| maplibre-gl's `Marker`, `ScaleControl` | Don't work — use `new map.Marker()`; a scale bar isn't available yet. |
| `hash`, `maxBounds`, `minPitch` / `maxPitch`, `transformRequest`, other projections, own styles | `createMap()` gives you the standard map (see [Which map you get](#which-map-you-get)). |

## Billing

The 3D map is billed exactly like the standard map: **one unit per map
session**, drawn from your single monthly [unit pool](/quotas). Terrain, 3D
buildings, trees and satellite imagery are included, and so is every
`setStyle` switch — also into another family (Streets → Outdoor or
Satellite). The one case that opens a new map session is a
[late fallback](#late-fallback) to the standard map.

As with any browser map, set an [allowed-origins list](/authentication) on the
key you ship to the browser.

## Attribution

The required data credits are shown on the map automatically (the
attribution control is on by default). Keep them visible; `map.attributions()`
on the 3D map returns the current list if you render your own credits.
