ts-maps

3D and the globe

On this page 12

Tilt a vector map and it turns 3D: buildings stand up, labels stay upright, and a sky comes in past the horizon. This page covers what you can add to that: buildings of your own, glTF landmarks, trees, sky and fog, the globe, and custom WebGL.

Elevation is on its own page. Hillshading, DEM sources and setTerrain are in Terrain.

All of it needs a vector basemap. The quickest is the built-in style over OpenFreeMap, which is free and needs no key:

import { Map, styles } from 'ts-maps'

const map = new Map('map', {
  center: [40.758, -73.9855], // Midtown Manhattan
  zoom: 16,
  pitch: 60,
  bearing: 20,
  style: styles.light({ url: 'https://tiles.openfreemap.org/planet' }),
})

That map already has 3D buildings. styles.light() and styles.dark() extrude OpenMapTiles buildings to their mapped render_height, and fade them in between zoom 14 and 15.

Pitch

map.setPitch(60)                        // jump
map.pitchTo(45, { duration: 600 })      // animate
map.easeTo({ pitch: 70, bearing: -30 }) // with the rest of the camera

setPitch tilts the map through a real perspective camera, the same one latLngToContainerPoint projects through. Streets converge towards the horizon, and everything placed by projection lines up with the tiles under it. Labels, markers, popups and tooltips stand upright at their projected points rather than lying flat on the ground.

Pitch is clamped to minPitch (default 0) and maxPitch (default 85, as in Apple Maps), both map options. Past about 72° the horizon comes into view. A sky is drawn above it, the theme's own or the one setSky sets, and the most distant ground fades into a haze beneath it. Labels too far off to read are left out. A drag, pan or zoom anchored near the horizon holds on to legible ground rather than flinging the map towards it.

Panning a tilted map moves the ground under a fixed camera: a drag keeps the point you grabbed under the pointer, and the horizon stays where it is.

Tiles are loaded for the ground the view actually sees, at a detail that falls off with distance: full detail near the camera, coarser tiles towards the horizon, where a full-detail tile would be a few pixels across. A 60° view needs about half the tiles it would at full detail, and loads the near ground first. A tile layer's detailLevels option (default 5) caps how many zoom levels coarser the distance may go; 0 keeps full detail throughout.

Buildings

The built-in styles draw buildings already. They come from fill-extrusion layers, which raise polygons into prisms, and a style of your own can have them too.

Fill-extrusion

To extrude buildings in a style of your own, add a fill-extrusion layer:

import { Map } from 'ts-maps'

const map = new Map('map', {
  center: [51.5072, -0.1276],
  zoom: 16,
  pitch: 55,
  style: {
    version: 8,
    sources: {
      planet: { type: 'vector', url: 'https://tiles.openfreemap.org/planet' },
    },
    layers: [
      { id: 'land', type: 'background', paint: { 'background-color': '#f4f1ea' } },
      {
        'id': 'buildings',
        'type': 'fill-extrusion',
        'source': 'planet',
        'source-layer': 'building',
        'minzoom': 14,
        'paint': {
          'fill-extrusion-color': '#d8d1c4',
          'fill-extrusion-height': ['coalesce', ['get', 'render_height'], 8],
          'fill-extrusion-base': ['coalesce', ['get', 'render_min_height'], 0],
          'fill-extrusion-opacity': ['interpolate', ['linear'], ['zoom'], 14, 0, 15, 1],
        },
      },
    ],
  },
})
Paint propertyDefault
fill-extrusion-color#000A colour, or an expression
fill-extrusion-height0Metres. Features where height is not above base are skipped
fill-extrusion-base0Metres
fill-extrusion-opacity10–1

Height, base and colour may be data-driven and are evaluated at the tile's zoom. Opacity is evaluated at the live zoom, so a layer can fade in smoothly as the example does. fill-extrusion-vertical-gradient is accepted by the style spec and ignored.

How they are drawn

  • Real camera. Buildings go into one viewport-sized WebGL canvas, with a projection identical to latLngToContainerPoint, over the tiles and under the labels. Each footprint sits exactly on its ground at any bearing or pitch. Seen straight down, tall buildings lean gently away from the centre, as a real camera sees them.
  • Lighting. Roofs are lifted slightly above the base colour. Walls are lit from the north-west and darken towards their foot, which separates a block of similar buildings into distinct boxes.
  • Distance. Buildings fade into the haze a few camera heights out, and tiles entirely past it are never meshed.
  • Labels behind buildings. A street name, or a point of interest with an icon, fades out when a building stands between it and the camera, and gives its space to labels that can be seen. Area names (districts, cities) have no single spot to hide and stay in view over the buildings.
  • Cost. Geometry is built once per source tile, shared by every grid tile that shows part of it past the source's top zoom, packed to 20 bytes a vertex and uploaded once. A frame is a matrix and a draw call per tile.

Where WebGL is unavailable, extrusions are drawn as flat footprints in their own colour.

Roof shapes

Where a building's tile carries its roof, it is drawn pitched rather than flat: OpenStreetMap's roof:shape and roof:height (or roof:levels), and Overture's roof_shape and roof_height. Gabled, hipped, pyramidal and skillion roofs are drawn as such; gambrel and saltbox as gables, mansard as a hip, domes and onions as pyramids. A gable's ridge runs along the footprint's long side (roof:orientation=across turns it), a skillion slopes down towards roof:direction, and with no height a roof is pitched at 30°. The walls rise to meet it, gable ends included.

OpenMapTiles tiles leave roof shapes out, so the built-in styles over them stay flat-roofed. A building over a courtyard, or cut by the tile edge, is also left flat. roofOf(properties) returns the roof a feature's properties describe, if you want to read them yourself.

Landmarks

A landmark is a glTF model standing where a building is, as Apple Maps swaps famous buildings' boxes for models of them.

import { landmark, Map, styles } from 'ts-maps'

const map = new Map('map', {
  center: [37.7959, -122.4034],
  zoom: 17,
  pitch: 52,
  bearing: -28,
  style: styles.light({ url: 'https://tiles.openfreemap.org/planet' }),
})

landmark({
  model: '/models/transamerica.glb',
  position: [37.7952, -122.4028],
  rotation: 0, // degrees clockwise; a glTF model faces south at 0
}).addTo(map)

It is drawn in the building pass: lit, fogged and depth-tested with the buildings, and labels behind it are hidden as they are behind a building. The extruded building it stands on is left out.

OptionDefault
modelA .glb or .gltf URL (its buffers are fetched beside it), a .glb's bytes, a parsed glTF with its buffers inline, or a model from loadModel
positionWhere the model's origin stands
altitude0Metres above the ground
rotation0Degrees clockwise
scale1glTF is in metres
replacetrueLeave out the extruded building under it. false keeps it
minZoom15Hidden zoomed out further than this
opacity1

setPosition, setRotation, setScale, setAltitude and setOpacity move and fade it; remove() takes it off the map. A model that fails to load logs a warning and leaves landmark.error set.

Models are read for their triangles, node transforms, vertex colours and baseColorFactor. Textures are not drawn, and Draco- or meshopt-compressed models are refused with an error saying so. loadModel, parseGLB and modelFromGltf are exported for loading a model once and placing it several times.

Trees

import { trees } from 'ts-maps'

trees().addTo(map)

Trees are planted in the woods the basemap already has (landcover class wood in OpenMapTiles, kind: forest in Protomaps and Shortbread), and as single trees where a source has them (natural=tree). They go on a jittered grid: the same trees in the same places every time, and none twice across a tile edge. Each is a trunk and a low-poly crown in one of a few greens.

OptionDefault
spacing9Metres between trees in a wood
minZoom15
minPitch20Degrees. Trees come in as the map tilts, and are not drawn looking straight down
maxPerTile3000Past this, every wood at that zoom is planted more thinly, evenly, so no tile edge shows
height[7, 14]Metres, [min, max]
colorsa few greensCrown colours
matchtreeKind(layer, properties) => 'wood' | 'tree' | undefined, for a schema the default does not know

Trees stop a few camera heights out, short of the haze, and each tile's trees are one mesh, built when they first come into view. setOptions changes them in place.

Landmarks and trees are drawn by the first vector tile layer on the map that reads from a tile server (the basemap, in a styled map), so they need a vector basemap and WebGL. Every framework binding has them as <Landmark> and <Trees>; see Framework bindings. The landmarks example has both running.

Sky and fog

map.setSky({
  'sky-color': '#87ceeb',
  'horizon-color': '#ffffff',
})

map.setFog({
  'color': 'rgb(245, 247, 250)',
  'horizon-blend': 0.1,
})

Sky and fog are a gradient over the tiles and under the labels and markers. It takes no pointer events.

  • Past the horizon (pitch above about 72°), the sky runs from sky-color at the top of the view to horizon-color at the horizon, then hazes over the most distant ground. Without setSky, the theme's own sky is used. Fog adds a band of color centred on the horizon, as wide as horizon-blend makes it.
  • Below that, the sky is a gradient down the top of the view and the fog a band across it, both fading in from 5° of pitch to full at 60°. A top-down map shows neither.
setSkyDefault
sky-color#87ceeb
horizon-color#ffffff
setFogDefault
colorrgb(245, 247, 250)On the globe, the halo, unless high-color is set
horizon-blend0.1Width of the fog band
high-colorOn the globe, the halo
space-colorOn the globe, the space around it

The two also accept Mapbox's range, star-intensity, fog-ground-blend, sun-position and sun-intensity. They are validated and kept, and returned by getFog() and getSky(), but nothing is drawn from them yet. setFog throws a RangeError when range[0] is not below range[1] or star-intensity is negative; setSky throws on NaN, and clamps fog-ground-blend and sun-intensity to [0, 1].

map.setFog(null) and map.setSky(null) turn them off. Each call fires fogchange ({ fog }) or skychange ({ sky }), including the null ones.

The globe

With projection: 'globe', the map zoomed out is a sphere. It is drawn with WebGL from the tiles the map has loaded, so every tile layer goes onto it as it is: the basemap, raster layers, hillshade and heatmaps.

import { Map, styles } from 'ts-maps'

const map = new Map('map', {
  center: [30, 10],
  zoom: 2.5,
  projection: 'globe',
  style: styles.light({ url: 'https://tiles.openfreemap.org/planet' }),
})

// The halo round it, and the space behind.
map.setFog({ 'color': '#ffffff', 'space-color': '#dfe7f0' })
  • Drag to turn it: the place you grabbed stays under the pointer.
  • Labels stand upright on it, and thin out towards the rim.
  • Markers, popups and tooltips sit on it and hide round the back.
  • Between zoom 5.5 and 6 it fades into the flat map. By then the globe's scale at the centre matches the flat map's, so the two line up.

Fog's color (or high-color) colours the halo and the haze at the rim, and space-color colours the space around the globe. Without WebGL, the flat map is shown with a halo round it. The globe example is the code above, running.

Switching projection at runtime

The projection can be set when the map is created, and changed at any time after:

map.setProjection('globe')
map.getProjection() // 'globe'
map.setProjection('mercator')

Nothing about the CRS changes: the projection is consulted while rendering, so this is a repaint rather than a rebuild, and the camera survives it. The map fires projectionchange with { projection }.

That matters because "show me the globe" is a view toggle a user presses, not a property of how the map was built.

Custom WebGL layers

A custom layer runs your own WebGL2 code inside the tile drawing. It is low level, and narrower than Mapbox's of the same name, so read the limits below before reaching for it.

import { Map, resolveTileJSON, vectorTileLayer } from 'ts-maps'

const map = new Map('map', { center: [51.5072, -0.1276], zoom: 12 })

// Custom layers are drawn by vector tile layers that use the WebGL renderer.
// OpenFreeMap publishes its current tile URL in a TileJSON.
const found = await resolveTileJSON('https://tiles.openfreemap.org/planet')
vectorTileLayer({
  url: found!.tiles,
  renderer: 'webgl',
  layers: [{ id: 'water', type: 'fill', sourceLayer: 'water', paint: { 'fill-color': '#9cc3e6' } }],
}).addTo(map)

map.addCustomLayer({
  id: 'tile-frames',
  type: 'custom',
  render(gl, matrix) {
    // Called once per tile, after the tile's own features, with that tile's
    // context and a matrix from tile pixels (0 to tileSize) to clip space.
  },
})
Member
idUnique. Adding a second layer with the same id throws
type'custom'
render(gl, matrix)Required. Errors are logged with console.warn and do not stop other custom layers
onAdd(map, gl), onRemove(map, gl)Optional. Called only when the map container's first canvas gives a WebGL2 context
renderingMode'2d' or '3d'. Accepted, not used

The limits, as the code stands:

  • render runs only inside a vectorTileLayer created with renderer: 'webgl'. The layers a style makes use Canvas2D, and map.setRenderer('webgl') does not switch them.
  • It runs once per tile, each with its own WebGL context, so buffers and programs made in one call (or in onAdd) belong to that context only.
  • The matrix is the tile's own, not the map camera's: it knows nothing of pitch or bearing.

map.getCustomLayer(id), map.getCustomLayers() and map.removeCustomLayer(id) look them up and take them off. The map fires customlayer:add and customlayer:remove with { id, layer }.

For things drawn in the map's own 3D camera, use a fill-extrusion layer or a landmark.

Try it