Elevation tiles 0.x
The terrain functions in the Maps guide read a grid of heights. This page gets one from the web: decode elevation tiles, stitch them into one grid, and tie the grid's cells to latitude and longitude, so you can put a rover, a landing site or a crash site on it.
import type { Radians } from '@interstellar-tools/types';
const toRad = (deg: number) => ((deg * Math.PI) / 180) as Radians;
const toDeg = (rad: number) => (rad * 180) / Math.PI;
const R = 6_378_137; // WGS 84's equatorial radius: Earth's tiles are cut for it, mThe example is the Matterhorn's summit, at 45.9763° N, 7.6586° E. Every number on this page is checked by a test.
Decode a tile
An elevation tile is a web map tile whose colours hold heights. Two encodings are common:
| Encoding | Height from red, green and blue | Step | Tiles |
|---|---|---|---|
'terrarium' | 1/256 m | Terrain Tiles on AWS, Mapzen | |
'terrain-rgb' | 0.1 m | Mapbox Terrain-RGB, MapTiler |
decodeElevationTile turns a tile's pixels, a canvas's ImageData, into a grid of heights in metres:
import { decodeElevationTile, tileAt } from '@interstellar-tools/maps';
const tile = tileAt(toRad(45.9763), toRad(7.6586), 12);
// { x: 2135, y: 1457, z: 12 }
const image = await createImageBitmap(
await (
await fetch(
`https://s3.amazonaws.com/elevation-tiles-prod/terrarium/${tile.z}/${tile.x}/${tile.y}.png`
)
).blob(),
{ colorSpaceConversion: 'none', premultiplyAlpha: 'none' }
);
const canvas = new OffscreenCanvas(image.width, image.height);
const context = canvas.getContext('2d')!;
context.drawImage(image, 0, 0);
const grid = decodeElevationTile(
context.getImageData(0, 0, image.width, image.height),
tile,
R
);
// 256 × 256 cells of 26.56 mA pixel of red 128, green 100 and blue 128 is 100.5 m; red 128 and nothing else is sea level. A transparent pixel is a missing cell, NaN.
The cell size comes from the tile's place on the Web Mercator map, at the latitude of its middle, so a grid's slopes are in true metres. Mercator stretches the map towards the poles, so the size is off by a little towards the tile's north and south edges: about 0.3% at 60° and zoom 10, and half that a zoom deeper. Use zoom 8 or deeper for terrain.
Read the pixels exactly
A flipped bit in the red channel is a jump of 256 m. Decode the image without colour management, as above, and never from a JPEG, whose compression changes the colours.
Some browsers add noise to what a canvas reads back, against fingerprinting: Brave, and Firefox with privacy.resistFingerprinting. In a web page for the public, prefer heights you've decoded ahead of time and serve as numbers, such as a Float32Array or Uint16Array file.
Stitch tiles
A tile is rarely where you want the edge of your map. stitchTiles puts a rectangle of tiles at one zoom into one grid, in any order, and gives its transform onto the map. Here are the 2 × 2 tiles round the summit:
import { stitchTiles } from '@interstellar-tools/maps';
const tiles = [];
for (const x of [2134, 2135])
for (const y of [1457, 1458]) tiles.push({ x, y, z: 12 });
const { grid, transform } = stitchTiles(
tiles.map((tile, i) => ({
tile,
grid: decodeElevationTile(images[i], tile, R)
})),
R
);
// 512 × 512 cells of 26.57 mThe cell size is taken at the middle of the whole block, so keep blocks a few tiles high. The tiles must fill the rectangle: stand in a grid of NaN for a tile you couldn't fetch. Tiles on both sides of the antimeridian don't form a rectangle, so stitch each side apart.
Find a place on the grid
A grid knows its cells' size, not where it is. A geotransform ties its rows and columns to a map, as a GeoTIFF's does:
(x₀, y₀) is the centre of the north-west cell on the map, and Δx, Δy the cells' size on the map. cellToMap and mapToCell run it both ways, and a projection takes the map to latitude and longitude. For a tile, tileGeoTransform gives the transform onto the Mercator map:
import {
cellToMap,
inverseMercator,
mapToCell,
mercator,
tileGeoTransform
} from '@interstellar-tools/maps';
const summit = mercator(toRad(45.9763), toRad(7.6586), R);
mapToCell(tileGeoTransform(tile, 256, 256, R), summit);
// ≈ { row: 150.11, column: 34.79 }: round both for the cell
mapToCell(transform, summit); // in the stitched grid
// ≈ { row: 150.11, column: 290.79 }: one tile, 256 cells, further east
const { x, y } = cellToMap(tileGeoTransform(tile, 256, 256, R), {
row: 0,
column: 0
});
inverseMercator(x, y, R); // ≈ 46.0121° N, 7.6467° E: the north-west cellWhole rows and columns are cells' centres, and ±0.5 their edges. A place off the grid gives a row or column outside it: check before you read the cell.
The map's cells aren't the ground's
The transform's cell size is on the map; the grid's own cellSize, which the terrain functions use, is on the ground. On a Mercator tile the map's cells are
Other grids
Elevation models for the Moon and Mars come as GeoTIFFs in their own projections. Their transform is in the file: the pixel scale, and a tie point that puts one pixel on the map. When the file says its pixels are areas, as most do, the tie point is the pixel's corner, so move it half a pixel to the centre.
A USGS CTX elevation model of Jezero has 20.163 m pixels on an equirectangular map of Mars's 3396.19 km sphere, tied at its corner (4 577 133.4 m, 1 146 178.5 m). Perseverance's landing site falls in it at:
import { equirectangular, mapToCell } from '@interstellar-tools/maps';
const pixel = 20.162955124498982;
const jezero = {
origin: { x: 4_577_133.445 + pixel / 2, y: 1_146_178.502 - pixel / 2 },
cellSize: { x: pixel, y: pixel }
};
mapToCell(jezero, equirectangular(toRad(18.4447), toRad(77.4508), 3_396_190));
// ≈ { row: 2621.86, column: 680.91 }The same cellToMap and the projection's inverse, here inverseEquirectangular, take any cell back to latitude and longitude. Check a transform against the edges the file's label gives before you trust it.
From an assistant
The MCP server's tile_for_point gives a point's pixel in its tile when given tile_size_px, and tile_info a pixel's latitude and longitude.
Next
- Contour lines: draw the grid as a topographic map.
decodeElevationTile,stitchTilesandtileGeoTransformin the reference.