Skip to content

Documentation / @interstellar-tools/maps / contours

Function: contours() ​

ts
function contours(
  grid: GridInterface,
  levels: readonly number[]
): ContourInterface[];

Defined in: terrain/contours.ts:103

Trace contour lines through a grid, such as an elevation model: the lines of equal height on a topographic map.

It runs marching squares over every square of four neighbouring cells, and puts each crossing on the square's edge by linear interpolation:

t=L−zazb−za

Where:

  • L is the contour's level
  • za and zb are the heights at the two ends of the edge, one at or above L and the other below
  • t is how far along the edge, from a, the contour crosses it

Units

  • Inputs: the grid's values and levels in the same units, m for an elevation grid.
  • Output: one ContourInterface for each level, in the order given, with points in grid coordinates: see GridPositionInterface.

Notes

  • Cells are points at their centres, so the lines run between the centres of the outer cells, not to the grid's edge.
  • A height exactly at a level counts as above it, so a flat area at that height is outlined rather than filled with lines.
  • A square with a missing cell has no contour, so a line stops where the data does. Lines are open there and at the grid's edge, and closed elsewhere.
  • Where two opposite corners are above the level and the other two below, a saddle, the square's mean height decides which pair the line joins.
  • Neighbouring squares compute a shared edge's crossing the same way, so the end of one segment is exactly the start of the next.

Parameters ​

ParameterTypeDescription
gridGridInterfaceThe grid, such as heights in m.
levelsreadonly number[]The heights to trace, in the grid's units (each finite).

Returns ​

ContourInterface[]

The contours, one for each level, in the order of levels.

Throws ​

  • If a size, cell size or level is not finite, or a value is infinite.
  • If the grid's parts don't fit together.

Example ​

ts
// A hill: a single peak in the middle of 3 × 3 cells of 10 m
const grid = createGrid({
  rows: 3,
  columns: 3,
  values: [0, 0, 0, 0, 10, 0, 0, 0, 0],
  cellSize: { x: 10, y: 10 }
});

// The 5 m contour: a diamond halfway between the peak and the cells around it
const [contour] = contours(grid, [5]);
contour.segments.length; // 4

See ​

https://en.wikipedia.org/wiki/Marching_squares Marching squares