Lattice Grid

api reference

Map View API Reference

createMapView: a 3D MapLibre and deck.gl map of a grid’s rows, as points, columns, polygons and flowing routes, kept in step with the grid’s own filter, search and selection.

API reference › The map view

All 30 pages Everything on one page → Developer guide →

The map view

modules/mapview puts a 3D map beside the grid that shows the same rows geographically, and keeps the two in step: the map is always a picture of the grid's current state, not a separate report. Any row with a place - a latitude and a longitude, a GeoJSON geometry, or a path of coordinates - is drawn; a filter, a quick search or a grouping on the grid redraws the map on the grid's next frame; selecting a row flies the map to it; clicking a feature selects its row and scrolls the grid to it; and hovering shows the row's cells in the grid's own formatted text. For a telecoms team, the build schedule, premises list or fault log they already manage in the grid becomes a 3D map of their network with no extra integration.

Option variants colour the markers. color: { field } with no map, on a column whose options carry a variant, draws each value in the theme's --lattice-variant-<name>-solid; a value the rule's map names still takes the map's colour, and a value with no variant takes the rule's usual colour.

import { createMapView } from '@toclocoinc/lattice-grid/modules/mapview';

const map = createMapView(grid, {
  container: '#map',                                     // or mode: 'split' | 'tab' | 'popout'
  geometry: { lat: 'latitude', lng: 'longitude' },       // or { geojson: 'geom' } or { path: 'route' }
  layer: 'column',                                       // 'point' | 'column' | 'polygon' | 'path'
  elevation: 'premisesPassed',
  color: { field: 'status', map: { live: '#2e7d32', build: '#f9a825', planned: '#90a4ae' } },
  buildings: true,
});

deck.gl and MapLibre stay yours. The module imports neither and ships no dependency. Load MapLibre GL and deck.gl on the page (their UMD builds set the globals maplibregl and deck), or pass them as libs: { deck, maplibregl }. The map is a MapLibre map, and the rows are deck.gl layers on it through deck's MapboxOverlay in interleaved mode, so deck's routes, areas, columns and points and MapLibre's 3D buildings share one depth buffer: a building in front of a route hides it at pitch 45 to 60. (deck.gl 9.1 reads the camera's depth planes under the names Mapbox GL uses, transform._nearZ and _farZ, and MapLibre GL 4.x names them nearZ and farZ; the module aliases them so the two agree. Looking straight down, at pitch 0, a roof is nearer the camera than anything under it, so a route under a building's footprint is hidden by its roof there too.) If either library is missing, mapview:libs warns, naming which one, and the map's box is left empty.

Where the rows are. geometry is { lat, lng } (or lon), { geojson } - a GeoJSON Geometry or Feature, as an object or its JSON text, or WKT or WKB - or { path }, an array of [lng, lat] pairs or its JSON text - or, for a network, { lat, lng, route: { by, order } } or { from: { lat, lng }, to: { lat, lng } } (see The network map). A row whose place is blank or cannot be read is skipped and counted: provenance() returns { drawn, skipped, matched, layers }, the rows drawn, the rows with no usable place, the rows the grid matched, and the count drawn by each layer kind.

How they look. A row is drawn by the layer for its geometry: a point is a marker (deck's ScatterplotLayer), or an extruded column (ColumnLayer) when an elevation is given; a polygon is an area (GeoJsonLayer), extruded when an elevation is given; a line is a route (PathLayer). layer picks the kind for the rows of its geometry, and setLayer() switches it live. elevation is a numeric column or one number, in metres, multiplied by elevationScale. color is one colour; { field, map }, a colour per value (any value not in map takes the next colour of the charts palette); or { field, scale: 'ramp', domain, colours, rampScale }, a number placed along a ramp by the charts module's own scale code, exactly as a heat map places it. Unset, rows take the grid theme's accent, and selected rows its focus colour. radius (a marker's, in metres) and width (a route's, in pixels) are a column or a number; a column layer draws every column at one radius, so only a number applies to it. A marker never draws larger than radiusMaxPixels (default 24 pixels) however far you zoom in, so a 30 m marker no longer covers a building; zoomed out it keeps its metres size, never under 3 pixels. Set radiusUnits: 'pixels' (default 'meters') to make radius a size on screen, the same at every zoom (for example radius: 8 draws a 16 pixel disc); picking, selection and moveRows work at that size. Example: createMapView(grid, { geometry: { lat: 'lat', lng: 'lng' }, radius: 8, radiusUnits: 'pixels' }). flow: true (or { speed, trail }) animates a flow along the routes; it stops while the page is hidden and is drawn still for a reader who prefers reduced motion.

Which rows: the grid's. The map draws the rows the grid shows after its filters and quick search - and, when it is grouped, every leaf row of the grouped result, whether or not its group is collapsed, because collapsing a group hides its rows from the table, not from the data. It is the same row path as the deck.gl adapter: a paged pushdown grid's map draws the rows inside the map's view, asked of the engine, up to viewportCap. A burst of grid changes costs one redraw, on the next animation frame.

Selection, both ways. A grid selection draws the selected rows in the highlight colour and flies the map to them: to the row, or to the box of several. flyTo(key) or flyTo([keys]) does the same from code. A click on a feature selects its row in the grid (selection: 'single' or 'multiple'; a grid that cannot take it warns mapview:selection), opens any collapsed group the row sits in, and scrolls it into view. Hovering a feature shows the tooltip columns (default the first three visible columns that do not hold the place; false for none), each as the grid's own display text for that cell, so a formatted value reads identically on the map and in the grid.

The basemap and buildings. basemap is a MapLibre style URL or style object; the default is OpenFreeMap's keyless positron, or its dark style for a dark theme. buildings: true adds 3D buildings from the style's OpenMapTiles building layer (render_height, render_min_height), coloured for the light or dark theme; a style with no vector source warns mapview:buildings. The first view fits the drawn rows; view: { center, zoom, pitch, bearing } sets it instead. fit chooses when the map fits itself to its rows: 'once' (the default) fits once at first draw and then leaves the camera to the reader; 'data' also re-fits - animated, debounced to one fit per 250 ms - whenever a filter or quick search changes the set of rows it draws, unless the reader has panned or zoomed since the last automatic fit, which stops it until fitToRows() is called; false never fits on its own. fitToRows() fits the map to the rows it is drawing now and re-arms the 'data' fit. theme is light or dark, by default the grid's own.

Where the map goes. mode: 'container' (the default when container, an element or a selector, is given) fills that element. 'split' (the default without one) puts the map beside the grid in the grid's own host, with a divider a pointer drags and the arrow keys move. 'tab' shows the grid and the map as two tabs. 'popout' opens the map in a separate browser window that runs on this page's libraries; when the browser blocks the popup, it opens in a floating panel instead, moved by its title bar, resized from its corner and closed by its button. destroy() removes the map, its layers and every listener, and puts the grid back where it was.

Events. on(name, fn) returns the unsubscribe and off(name, fn) removes a listener: feature:click ({ key, row }, and for a route route and keys), feature:hover ({ key, row, lines }), draw ({ provenance }), load (the basemap style loaded) and close (the reader closed a popped-out map). update(options) changes options and redraws now; layers() returns the deck.gl layers last handed to the map.

The mapView key in a grid's own configuration is not offered: the grid has no means for a module to add a configuration key, so the map view is made by createMapView(grid, options) once the grid exists.

The network map: routes from rows, dashes, icons

A fibre, pipe or power network is usually not one row per line: it is a table of points, each row one vertex of a route, plus the cabinets and joints that sit on it. The map view draws that table as it is. The recipe below puts the routes, their vertex rows and the cabinet points in one view: routes assembled from the vertex rows, coloured and dashed by their status, cabinets as icons on badges, all readable in the 3D presentation among extruded buildings.

createMapView(grid, {
  container: '#map',
  geometry: { lat: 'lat', lng: 'lng', route: { by: 'routeId', order: 'seq' } },
  color: { field: 'status', map: { live: '#2e9d4f', planned: '#1f6fd1', backbone: '#d62828', proposed: '#d62828' } },
  dash: { field: 'status', map: { proposed: 'dashed', planned: 'dotted', live: 'solid' } },
  width: 4,
  icon: { field: 'kind', map: { cabinet: 'cabinet', splice: 'splice', exchange: 'exchange' }, size: 26, badge: 'diamond' },
  legend: true,
  buildings: true,                                       // the default 3D presentation: pitched, with extruded buildings
});

Routes from rows. With route: { by, order }, every row that has a place and a non-blank by value is one vertex of the route that value names. Each route is one line through its vertices in order (numbers as numbers, anything else as text, a blank last; without order, the grid's row order). A route whose rows are given in any order is still drawn in sequence. The rule that tells a vertex from a point is the route id: a row belongs to a route only when it has a route id. A row with a blank route id (null or empty) is not a vertex; it stays a point - a cabinet, a splice - and is drawn as one, so vertex rows and cabinet rows share a grid. A vertex row is never also drawn as a point.

A route's colour, width, dash and elevation are route-level: the value in the route's first vertex row (in sequence order), or, with route: { aggregate }, the last, min or max across its rows. A route with fewer than two usable vertices (a vertex row with no usable place does not count) is skipped, and counted: provenance() adds routes, routesSkipped and routesRebuilt, and the skipped route's rows are in skipped, so drawn + skipped is every matched row. The segment form, { from: { lat, lng }, to: { lat, lng } }, draws each row as one line from its from to its to, with no route id; a row missing an end is skipped.

Live. A filter, an edit, an add or a delete of a vertex row assembles again only that route: every other route is reused as it was, and provenance().routesRebuilt says how many were assembled on the last draw. Clicking a route selects every one of its rows in the grid (the grid needs selection: 'multiple' to hold them all), and selecting any of a route's rows draws the route in the highlight colour. Hovering a route shows its route id first, then the tooltip columns of its first row, each in the grid's own formatted text.

Dashed lines. dash is 'dashed' or 'dotted' for every line, [dash, gap] in pixels, or { field, map } naming a pattern per value (a value not named is solid). The pattern is in pixels and keeps its length on screen as the camera zooms and pitches. Dashes are drawn by deck.gl's PathStyleExtension, which the page supplies with deck (the standalone deck.gl bundle exports it); without it mapview:dash warns and the lines are solid. legend: true draws the legend in the map's box. When the colour rule and the dash rule key on the same field (color: { field: 'status', map } and dash: { field: 'status', map: { proposed: 'dashed' } }) the legend has one entry per value, its sample a short line in that value's colour and dash pattern (a solid value is a solid line); a value drawn only as points is a square swatch. When they key on different fields the legend keeps two sections, each titled by its field's column header. legend() returns { sections, colours, dashes }: sections is what is drawn ({ field, title, merged, entries: [{ label, colour, dash, line }] }), colours and dashes are the two rules' own entries.

Icon markers. icon: { field, map, default, size, anchor, badge } draws point rows with deck's IconLayer instead of circles. A point's icon is map[value], else default; the glyphs are the grid's icon registry - the same one a network chart's node icons use - which now includes cabinet, splice, exchange, pole, chamber, premises and fault, or an SVG path, an icon definition, or an image URL. Registry glyphs are tinted by the color mapping, or, with badge: 'circle' | 'square' | 'diamond', drawn white on a badge of that colour with a white ring (the red diamonds of a network map); the badge is what picks, hovers and selects, as a point does. Every icon is packed once into one atlas at 64 pixels a glyph, sharp at 2x, and repacked only when a point asks for an icon the atlas does not hold. An unknown name warns mapview:icon:<name> and its point is a circle.

Readable in 3D. Routes are drawn in pixels, between 2 and 30 pixels wide whatever the width, so they stay clear at street level, and 2 m above the ground (points 4 m, when routes are in view) so a route does not z-fight the basemap at pitch 45 to 60. Icons are billboards that always face the camera and keep their pixel size; they are not depth-tested, so an icon is drawn whole over the ground, the routes and the extruded buildings - a cabinet inside a building's footprint is never hidden by it. The draw order is polygons, then routes (and their flow), then columns, then points, then icons: points over lines over areas.

A network map: routes assembled from vertex rows in sequence order, dashed by status, a route selecting all its rows, and an edit assembling one route again

const { createTestDom, flushFrames } = await import('../packages/dom/src/renderer/testdom.js');
const { createHeadlessGrid } = await import('../packages/core/src/index.js');
const { createMapView } = await import('../packages/modules/mapview/index.js');

const dom = createTestDom();
const el = dom.document.createElement('div');
dom.root.appendChild(el);
const grid = createHeadlessGrid({
  rowKey: 'id',
  selection: 'multiple',
  columns: [{ field: 'id' }, { field: 'routeId' }, { field: 'seq', type: 'number' }, { field: 'status' }, { field: 'kind' },
    { field: 'lat', type: 'number' }, { field: 'lng', type: 'number' }],
  rows: [
    // Two routes, their vertex rows out of order, and a cabinet that is on no route.
    { id: 'a3', routeId: 'R1', seq: 3, status: 'live', lat: 51.884, lng: 0.904 },
    { id: 'a1', routeId: 'R1', seq: 1, status: 'live', lat: 51.880, lng: 0.900 },
    { id: 'a2', routeId: 'R1', seq: 2, status: 'live', lat: 51.882, lng: 0.901 },
    { id: 'b2', routeId: 'R2', seq: 2, status: 'proposed', lat: 51.889, lng: 0.909 },
    { id: 'b1', routeId: 'R2', seq: 1, status: 'proposed', lat: 51.885, lng: 0.905 },
    { id: 'c1', routeId: null, seq: null, status: 'live', kind: 'cabinet', lat: 51.882, lng: 0.901 },
  ],
});

// The icon atlas is drawn on a canvas, which a page has. This stand-in canvas just accepts the drawing.
const make = dom.document.createElement.bind(dom.document);
dom.document.createElement = (tag) => {
  const el = make(tag);
  if (tag === 'canvas') {
    el.getContext = () => new Proxy({}, { get: () => () => {} });
    el.toDataURL = () => 'data:image/png;base64,atlas';
  }
  return el;
};
globalThis.Path2D ??= class { constructor(d) { this.d = d; } };

// Stand-ins for the page's deck.gl and MapLibre, as above; PathStyleExtension is
// what draws the dashes, and the page's deck supplies it.
const layer = (kind) => class { constructor(props) { this.props = props; this.kind = kind; } };
const deck = {
  ScatterplotLayer: layer('point'), ColumnLayer: layer('column'), GeoJsonLayer: layer('polygon'),
  PathLayer: layer('path'), TripsLayer: layer('flow'), IconLayer: layer('icon'), PathStyleExtension: layer('dash'),
  MapboxOverlay: class { constructor(p) { this.props = p; } setProps(p) { Object.assign(this.props, p); } },
};
const maplibregl = {
  Map: class {
    on() {} off() {} addControl() {} removeControl() {} remove() {} resize() {} setStyle() {}
    getZoom() { return 12; } getBounds() { return null; } getStyle() { return { sources: {} }; }
    getLayer() {} addLayer() {} jumpTo() {} fitBounds() {} flyTo() {}
  },
};

const map = createMapView(grid, {
  container: el,
  libs: { deck, maplibregl },
  geometry: { lat: 'lat', lng: 'lng', route: { by: 'routeId', order: 'seq' } },
  color: { field: 'status', map: { live: '#2e9d4f', proposed: '#d62828' } },
  dash: { field: 'status', map: { proposed: 'dashed', live: 'solid' } },
  width: 4,
  icon: { field: 'kind', map: { cabinet: 'cabinet' }, size: 26, badge: 'diamond' },
  legend: true,
});
const routes = map.layers().find((l) => l.kind === 'path');
const r1 = routes.props.data.find((d) => d.item.route === 'R1');
const seen = [
  `${map.provenance().routes} routes`,
  routes.props.getPath(r1).map((p) => p[1]).join(','),            // in seq order, not row order
  map.legend().dashes.map((d) => `${d.label} ${d.dash ? d.dash.join('/') : 'solid'}`).join(' + '),       // dash and gap, in pixels
  map.layers().find((l) => l.kind === 'icon').props.data.map((d) => d.icon).join(),                 // the cabinet is an icon
];

map.overlay.props.onClick({ object: r1 });                         // a route selects all its rows
seen.push(grid.selection.keys().sort().join());

grid.rows.apply({ update: [{ id: 'b1', lat: 51.8855 }] });         // an edit assembles one route again
flushFrames();
seen.push(map.provenance().routesRebuilt);

map.destroy();
return seen.join(' | ');

Rows to the map, a filter followed, a selection flown to, the grid's own text on hover, a click selecting, a layer switched, and destroy

const { createTestDom, flushFrames } = await import('../packages/dom/src/renderer/testdom.js');
const { createHeadlessGrid } = await import('../packages/core/src/index.js');
const { createMapView } = await import('../packages/modules/mapview/index.js');

const dom = createTestDom();
const el = dom.document.createElement('div');
dom.root.appendChild(el);
const grid = createHeadlessGrid({
  rowKey: 'id',
  selection: 'single',
  columns: [{ field: 'id' }, { field: 'status' }, { field: 'passed', type: 'number' },
    { field: 'cost', type: 'number', format: { style: 'currency', decimals: 0, locale: 'en-US' } },
    { field: 'lat', type: 'number' }, { field: 'lng', type: 'number' }],
  rows: Array.from({ length: 30 }, (_, i) => ({
    id: 'p' + i, status: ['planned', 'build', 'live'][i % 3], passed: (i % 10) + 1,
    cost: 900 + i * 25, lat: 51.88 + (i % 6) * 0.002, lng: 0.89 + Math.floor(i / 6) * 0.003,
  })),
});

// Stand-ins for the page's deck.gl and MapLibre: a layer keeps its props, the
// overlay keeps the layers, the map records its camera. On a page these are
// the UMD globals `deck` and `maplibregl`, and `libs` is not needed.
const layer = (kind) => class { constructor(props) { this.props = props; this.kind = kind; } };
const deck = {
  ScatterplotLayer: layer('point'), ColumnLayer: layer('column'), GeoJsonLayer: layer('polygon'),
  PathLayer: layer('path'), TripsLayer: layer('flow'),
  MapboxOverlay: class { constructor(p) { this.props = p; } setProps(p) { Object.assign(this.props, p); } },
};
const camera = [];
const maplibregl = {
  Map: class {
    on() {} off() {} addControl() {} removeControl() {} remove() {} resize() {} setStyle() {}
    getZoom() { return 12; } getBounds() { return null; } getStyle() { return { sources: {} }; }
    getLayer() {} addLayer() {} jumpTo(o) { camera.push('jump ' + o.zoom); }
    fitBounds() { camera.push('fit'); } flyTo(o) { camera.push('fly ' + o.center.join(',')); }
  },
};

const map = createMapView(grid, {
  container: el,
  mode: 'container',
  libs: { deck, maplibregl },
  geometry: { lat: 'lat', lng: 'lng' },
  layer: 'column',
  elevation: 'passed',
  elevationScale: 20,
  radius: 15,
  width: 3,
  color: { field: 'status', map: { live: '#2e7d32', build: '#f9a825', planned: '#90a4ae' } },
  flow: false,                                     // routes only: an animated flow along them
  buildings: true,
  basemap: 'https://tiles.openfreemap.org/styles/positron',
  fit: 'data',                                     // refit when a filter changes the rows
  theme: 'light',
  tooltip: ['status', 'cost'],
  viewportCap: 20000,                              // a paged pushdown grid: rows fetched for the view
});
const seen = [`${map.provenance().drawn} ${map.layers()[0].kind} ${camera.at(-1)}`];

grid.filters.set({ col: 'status', op: 'eq', value: 'live' });
flushFrames();                                     // the map redraws on the grid's next frame
seen.push(map.provenance().drawn);

grid.selection.set(['p5']);                        // a grid selection flies the map
seen.push(camera.at(-1));

const tips = [];
map.on('feature:hover', (e) => tips.push(e.lines.map((l) => l.text).join(' ')));
map.overlay.props.onHover({ object: map.layers()[0].props.data[0], x: 0, y: 0 });
seen.push(tips[0]);                                // the grid's own cell text

map.overlay.props.onClick({ object: map.layers()[0].props.data[2] });
seen.push(grid.selection.keys()[0]);               // a click selects the row

map.setLayer('point');
seen.push(map.layers()[0].kind);
map.flyTo(['p2', 'p8']);
seen.push(camera.at(-1));

map.fitToRows();                                   // fit now, and re-arm the automatic fit
seen.push('fitToRows ' + camera.at(-1));

const draws = [];
const onDraw = (e) => draws.push(e.provenance.drawn);
map.on('draw', onDraw);
map.update({ view: { zoom: 14, pitch: 60 } });
map.off('draw', onDraw);
map.update({});
seen.push(`${camera.at(-1)} ${draws.join()}`);

map.destroy();
seen.push(el.children.length);
return seen.join(' | ');

Map view: drawing and editing

mapView.draw draws and edits shapes on the map itself - points, lines, polygons, circles and rectangles - in a layer above the data layers, styled from the map view's own theme roles. All three parts of are here: creating shapes, selecting, editing, moving, deleting and undoing them, and the precision work - snapping, constraints, a measurement readout and touch.

map.draw.setMode('polygon');                           // 'point' | 'line' | 'polygon' | 'circle' | 'rectangle' | null
map.on('draw:finish', (e) => console.log(e.feature));  // a GeoJSON Feature, with a generated id

Switching modes. setMode(mode, options) switches what a click or a drag draws, at runtime; null turns drawing off. options.properties is merged onto every feature the mode finishes, until the mode changes again. Escape cancels the shape in progress without drawing it; so does calling setMode again.

Building a shape. A click places a point, or adds a vertex to the line or polygon in progress; a double-click, or a click back on the first vertex, finishes it - a polygon's ring is always closed, and the double-clicked point is the last vertex (clicking a point and then double-clicking the same spot adds it once), and a double-click on a point a constraint refuses rejects it and leaves the shape open. A circle is dragged from its centre: its feature carries properties.center and properties.radius (in metres) alongside the polygon that approximates it. A rectangle is dragged corner to corner. None of this changes the grid's rows.

Events. draw:start fires when a shape begins (a point's own click, a line or polygon's first vertex, or a circle or rectangle's drag starting); draw:change as it grows (a vertex added, or the drag moving); draw:finish once, with the finished Feature. map:click fires on every click on the map, drawing or not: { lng, lat, features }, the data rows under the cursor.

Reading and replacing shapes. getFeatures() returns every finished shape as a GeoJSON FeatureCollection; setFeatures(geojson) replaces them (a FeatureCollection or a bare array of Features), giving any feature with no id one; clear() removes them all. Each feature's properties.readonly (false for a shape the reader drew) is respected by edit mode: a readonly shape shows no handles and is never moved or deleted. mapView.getMap() is the MapLibre map itself - the escape hatch for anything this module does not wrap.

Editing. setMode('edit') selects and edits the drawn shapes. A click selects a shape, Shift-click adds (or removes) one, a click on empty map or Escape clears the selection, and Delete or Backspace deletes the selected shapes. A selected line or polygon shows a handle on each vertex and a smaller one on each segment's midpoint: drag a vertex handle to move it, drag a midpoint to insert a vertex there, Alt-click (Option on macOS) a vertex - or click it and press Delete - to remove it, never below 2 vertices for a line or 3 for a polygon. Dragging a shape's body moves every selected shape. A circle has no vertex handles (its body still moves, and its properties.center with it), and a shape with properties.readonly can be selected but shows no handles and is never moved or deleted. Selected shapes and handles are painted from the map view's theme roles, so they follow light and dark.

Undo and redo. Every create, edit, move and delete is one step: Ctrl/Cmd-Z undoes it, Ctrl/Cmd-Shift-Z (or Ctrl-Y) redoes it, and draw.undo() / draw.redo() do the same from code, for up to 100 steps. setFeatures() and clear() start a new history. Undo and redo fire no event of their own; read getFeatures().

Edit events. edit:change fires on release with { id, geometry, feature } - once per vertex drag, midpoint insert, vertex removal, or (for a move of several shapes) per shape moved. feature:select fires with { ids } whenever the selection changes; feature:delete fires once with { ids } for the shapes a Delete removed.

Snapping. setMode(mode, { snap: { layers: ['chambers'], tolerance: 10 } }) snaps a new or moved vertex to the vertices, then the segments, of the features on those layers within tolerance pixels (default 10). A layer id names one of the page's own MapLibre layers - added with mapView.getMap(); a GeoJSON source given as an object snaps to its exact coordinates - or the drawn features whose properties.layer is that id (set it with setMode's properties option). A vertex that snaps to a vertex takes that vertex's coordinates exactly, so a route can end on a chamber point and a cable can follow a route; a ring marks the target while the pointer is near it. Snapping works in 'edit' mode too, for a dragged vertex.

Constraints. setMode(mode, { constraints }) keeps a shape within rules: geometryTypes ('Point', 'LineString', 'Polygon': the types the mode may draw), maxVertices, minSegmentLength (metres between neighbouring vertices) and noSelfIntersection (a polygon may not cross itself). A vertex that would break one is refused: it is not added or moved, a ring marks the spot, the readout says why for a moment, and draw:refused fires with { mode, rule, position }, where rule is 'geometry-type', 'max-vertices', 'min-segment-length' or 'self-intersection'.

Measurement. While a shape is drawn or edited, a readout beside the cursor gives a line's length and its active segment (m below 1 km, then km) or a polygon's or circle's area and perimeter (m² below 1 ha, then ha), in the grid's locale number format (so 1.00 km in en-GB, 1,00 km in de-DE). It stays inside the map, follows the light or dark theme, and lingers on a finished shape until the pointer moves.

Touch. Drawing and editing work on a tablet: tap to add a vertex, long-press to finish a line or polygon, drag a vertex or midpoint handle with one finger (handles are at least 24px touch targets, larger once a finger has touched the map), and long-press a vertex handle to remove it. Two fingers always pan and zoom the map, and never add a vertex.

Drawing a point, a line closed by clicking its first vertex, a polygon finished by a double-click, and a circle dragged from its centre; a setFeatures/getFeatures round trip; getMap()

const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createHeadlessGrid } = await import('../packages/core/src/index.js');
const { createMapView } = await import('../packages/modules/mapview/index.js');

const dom = createTestDom();
const el = dom.document.createElement('div');
dom.root.appendChild(el);
const grid = createHeadlessGrid({
  rowKey: 'id',
  columns: [{ field: 'id' }, { field: 'lat', type: 'number' }, { field: 'lng', type: 'number' }],
  rows: [{ id: 'p1', lat: 51.88, lng: 0.9 }],
});

// Stand-ins for the page's deck.gl and MapLibre: real enough to drive the draw
// layer's own event handlers directly, the way a reader's mouse would.
const layer = (kind) => class { constructor(props) { this.props = props; this.kind = kind; } };
const deck = {
  ScatterplotLayer: layer('point'), ColumnLayer: layer('column'), GeoJsonLayer: layer('polygon'),
  PathLayer: layer('path'), TripsLayer: layer('flow'),
  MapboxOverlay: class { constructor(p) { this.props = p; } setProps(p) { Object.assign(this.props, p); } },
};
const toggle = { enable() {}, disable() {} };
const maplibregl = {
  Map: class {
    constructor() { this.handlers = {}; this.doubleClickZoom = toggle; this.dragPan = toggle; this.dragRotate = toggle; this.boxZoom = toggle; }
    on(type, fn) { this.handlers[type] = fn; } off() {} addControl() {} removeControl() {} remove() {} resize() {} setStyle() {}
    getZoom() { return 12; } getBounds() { return null; } getStyle() { return { sources: {} }; } getPitch() { return 0; }
    getLayer() {} addLayer() {} jumpTo() {} fitBounds() {} flyTo() {}
    // A flat, invertible fake projection: good enough for the draw layer's own "near the first vertex" check.
    project([lng, lat]) { return { x: lng * 1000, y: lat * 1000 }; }
  },
};

const map = createMapView(grid, { container: el, libs: { deck, maplibregl }, geometry: { lat: 'lat', lng: 'lng' } });
const m = map.map;
const click = (lng, lat, detail = 1) => m.handlers.click({ lngLat: { lng, lat }, point: { x: lng * 1000, y: lat * 1000 }, originalEvent: { detail } });
const seen = [];

map.draw.setMode('point', { properties: { source: 'reader' } });
map.on('draw:finish', (e) => {
  const f = e.feature;
  seen.push(f.properties.shape === 'circle'
    ? `${f.properties.shape} r=${f.properties.radius.toFixed(1)}m verts=${f.geometry.coordinates[0].length}`
    : `${f.properties.shape}${f.properties.source ? ':' + f.properties.source : ''} ${f.geometry.coordinates.flat().join(',')}`);
});
click(0.90, 51.88);                                 // a point finishes on its own click; its properties carry setMode's options

map.draw.setMode('line');
click(0.90, 51.88); click(0.91, 51.88); click(0.92, 51.88);
click(0.90, 51.88);                                 // clicking back on the first vertex finishes the line

map.draw.setMode('polygon');
click(0.90, 51.88); click(0.91, 51.88); click(0.91, 51.89); click(0.90, 51.89);
click(1.0, 52.0, 1); m.handlers.dblclick({ lngLat: { lng: 1.0, lat: 52.0 }, point: { x: 1000, y: 52000 } }); // a double-click finishes it, adding no vertex of its own

map.draw.setMode('circle');
m.handlers.mousedown({ lngLat: { lng: 0.9, lat: 51.88 } });
m.handlers.mousemove({ lngLat: { lng: 0.901, lat: 51.88 } });
m.handlers.mouseup({});

seen.push(`${map.draw.getFeatures().features.length} shapes`);
seen.push(map.draw.getFeatures().features.map((f) => f.properties.shape).join(','));

map.draw.setFeatures({ type: 'FeatureCollection', features: [
  { type: 'Feature', id: 'a', geometry: { type: 'Point', coordinates: [1, 2] }, properties: { shape: 'point', readonly: true } },
] });
seen.push(`${map.draw.getFeatures().features.length} after setFeatures, readonly=${map.draw.getFeatures().features[0].properties.readonly}`);

map.draw.clear();
seen.push(`${map.draw.getFeatures().features.length} after clear`);
seen.push(map.getMap() === map.map);

map.destroy();
return seen.join(' | ');

Editing: select two shapes, delete them with the Delete key, undo and redo, and a readonly shape that ignores Delete

const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createHeadlessGrid } = await import('../packages/core/src/index.js');
const { createMapView } = await import('../packages/modules/mapview/index.js');

const dom = createTestDom();
const el = dom.document.createElement('div');
dom.root.appendChild(el);
const grid = createHeadlessGrid({
  rowKey: 'id',
  columns: [{ field: 'id' }, { field: 'lat', type: 'number' }, { field: 'lng', type: 'number' }],
  rows: [{ id: 'p1', lat: 51.88, lng: 0.9 }],
});

// Stand-ins for the page's deck.gl and MapLibre, as in the drawing example above.
const layer = (kind) => class { constructor(props) { this.props = props; this.kind = kind; } };
const deck = {
  ScatterplotLayer: layer('point'), ColumnLayer: layer('column'), GeoJsonLayer: layer('polygon'),
  PathLayer: layer('path'), TripsLayer: layer('flow'),
  MapboxOverlay: class { constructor(p) { this.props = p; } setProps(p) { Object.assign(this.props, p); } },
};
const toggle = { enable() {}, disable() {} };
const maplibregl = {
  Map: class {
    constructor() { this.handlers = {}; this.doubleClickZoom = toggle; this.dragPan = toggle; this.dragRotate = toggle; this.boxZoom = toggle; }
    on(type, fn) { this.handlers[type] = fn; } off() {} addControl() {} removeControl() {} remove() {} resize() {} setStyle() {}
    getZoom() { return 12; } getBounds() { return null; } getStyle() { return { sources: {} }; } getPitch() { return 0; }
    getLayer() {} addLayer() {} jumpTo() {} fitBounds() {} flyTo() {}
    project([lng, lat]) { return { x: lng * 1000, y: lat * 1000 }; }
  },
};

const map = createMapView(grid, { container: el, libs: { deck, maplibregl }, geometry: { lat: 'lat', lng: 'lng' } });
const m = map.map;
const click = (lng, lat, shiftKey = false) => m.handlers.click({ lngLat: { lng, lat }, point: { x: lng * 1000, y: lat * 1000 }, originalEvent: { detail: 1, shiftKey } });
const key = (k, extra = {}) => dom.document.dispatchEvent({ type: 'keydown', key: k, bubbles: true, target: null, preventDefault() {}, stopPropagation() {}, ...extra });
const point = (id, lng, readonly) => ({ type: 'Feature', id, geometry: { type: 'Point', coordinates: [lng, 51.88] }, properties: { shape: 'point', readonly } });
const seen = [];

map.on('feature:select', (e) => { if (e.ids.length > 1) seen.push(`selected ${e.ids.join(',')}`); });
map.on('feature:delete', (e) => seen.push(`deleted ${e.ids.join(',')}`));
map.draw.setFeatures([point('a', 0.90, false), point('b', 0.91, false), point('c', 0.92, true)]);
map.draw.setMode('edit');

click(0.90, 51.88);                                 // a click selects a shape
click(0.91, 51.88, true);                           // Shift-click adds one: feature:select now reports both
key('Delete');                                      // Delete removes the selected shapes: one feature:delete with both ids
seen.push(`${map.draw.getFeatures().features.length} left`);

map.draw.undo();                                    // the same as Ctrl/Cmd-Z
seen.push(`undo ${map.draw.getFeatures().features.length}`);
map.draw.redo();
seen.push(`redo ${map.draw.getFeatures().features.length}`);

click(0.92, 51.88); key('Delete');                  // a readonly shape can be selected but is never deleted
seen.push(map.draw.getFeatures().features.some((f) => f.id === 'c') ? 'readonly kept' : 'readonly lost');

map.destroy();
return seen.join(' | ');

Precision: a line vertex snapped to a chamber layer, one dropped too far away left alone, and a polygon vertex refused for crossing the polygon

const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createHeadlessGrid } = await import('../packages/core/src/index.js');
const { createMapView } = await import('../packages/modules/mapview/index.js');

const dom = createTestDom();
const el = dom.document.createElement('div');
dom.root.appendChild(el);
const grid = createHeadlessGrid({
  rowKey: 'id',
  columns: [{ field: 'id' }, { field: 'lat', type: 'number' }, { field: 'lng', type: 'number' }],
  rows: [{ id: 'p1', lat: 51.88, lng: 0.9 }],
});

// Stand-ins for the page's deck.gl and MapLibre, as in the drawing example above.
const layer = (kind) => class { constructor(props) { this.props = props; this.kind = kind; } };
const deck = {
  ScatterplotLayer: layer('point'), ColumnLayer: layer('column'), GeoJsonLayer: layer('polygon'),
  PathLayer: layer('path'), TripsLayer: layer('flow'),
  MapboxOverlay: class { constructor(p) { this.props = p; } setProps(p) { Object.assign(this.props, p); } },
};
const toggle = { enable() {}, disable() {} };
const maplibregl = {
  Map: class {
    constructor() { this.handlers = {}; this.doubleClickZoom = toggle; this.dragPan = toggle; this.dragRotate = toggle; this.boxZoom = toggle; }
    on(type, fn) { this.handlers[type] = fn; } off() {} addControl() {} removeControl() {} remove() {} resize() {} setStyle() {}
    getZoom() { return 12; } getBounds() { return null; } getStyle() { return { sources: {} }; } getPitch() { return 0; }
    getLayer() {} addLayer() {} jumpTo() {} fitBounds() {} flyTo() {}
    project([lng, lat]) { return { x: lng * 1000, y: lat * 1000 }; }
  },
};

const map = createMapView(grid, { container: el, libs: { deck, maplibregl }, geometry: { lat: 'lat', lng: 'lng' } });
const m = map.map;
const click = (lng, lat) => m.handlers.click({ lngLat: { lng, lat }, point: { x: lng * 1000, y: lat * 1000 }, originalEvent: { detail: 1 } });
const seen = [];
const snap = { layers: ['chambers'], tolerance: 10 };

// A chamber on the 'chambers' snap layer: a drawn point whose properties.layer names it.
map.draw.setFeatures([{ type: 'Feature', id: 'ch', geometry: { type: 'Point', coordinates: [0.9, 51.88] }, properties: { shape: 'point', readonly: true, layer: 'chambers' } }]);

map.draw.setMode('line', { snap });
click(0.80, 51.80); click(0.906, 51.88);            // 6px from the chamber: it takes the chamber's coordinates exactly
click(0.95, 51.90); click(0.80, 51.80);             // back on the first vertex: finish
seen.push(`snapped ${map.draw.getFeatures().features.find((f) => f.properties.shape === 'line').geometry.coordinates[1].join(',')}`);

map.draw.setMode('line', { snap });
click(0.50, 51.50); click(0.92, 51.88);             // 20px away: too far to snap
click(0.95, 51.90); click(0.50, 51.50);
seen.push(`unsnapped ${map.draw.getFeatures().features.filter((f) => f.properties.shape === 'line')[1].geometry.coordinates[1].join(',')}`);

map.on('draw:refused', (e) => seen.push(`refused ${e.rule}`));
map.draw.setMode('polygon', { constraints: { noSelfIntersection: true } });
click(0.80, 51.80); click(0.90, 51.90); click(0.90, 51.80);
click(0.80, 51.90);                                 // this vertex would make the polygon cross itself: refused
click(0.80, 51.80);                                 // the first vertex closes the triangle
seen.push(`triangle ${map.draw.getFeatures().features.find((f) => f.properties.shape === 'polygon').geometry.coordinates[0].length} positions`);

map.destroy();
return seen.join(' | ');

Moving a grid row. The drawn shapes are the map view's own, but the grid's rows can be moved too. Set moveRows: true (off by default) and, in edit mode, a row placed by geometry: { lat, lng } shows the move cursor when the pointer is over its point; drag it and the point follows, and on release the new latitude and longitude are written through the grid's own editing path (grid.edit.setCells, origin 'user'), exactly as if they had been typed into the two cells. The column's validation, beforeEdit, the grid's undo, its change events and a server write-back all apply, and the two cells are one edit and one undo step. An edit the grid refuses puts the point back where it was. A row whose latitude or longitude cell cannot be edited (a read-only column, row or grid) shows no move cursor and cannot be dragged. With moveRows off a drag on a row pans the map as before, and the drawn shapes behave the same either way. Only rows placed by latitude and longitude move; rows placed by a geojson or path column do not.

Moving a row: with moveRows on, dragging its point writes both cells as one edit, and one grid undo puts them back

const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createHeadlessGrid } = await import('../packages/core/src/index.js');
const { createMapView } = await import('../packages/modules/mapview/index.js');

const dom = createTestDom();
const el = dom.document.createElement('div');
dom.root.appendChild(el);
const grid = createHeadlessGrid({
  rowKey: 'id',
  columns: [{ field: 'id' }, { field: 'lat', type: 'number', edit: true }, { field: 'lng', type: 'number', edit: true }],
  rows: [{ id: 'cabinet-7', lat: 51.88, lng: 0.9 }],
});

// Stand-ins for the page's deck.gl and MapLibre, as in the drawing example above, with a canvas to press on.
const layer = (kind) => class { constructor(props) { this.props = props; this.kind = kind; } };
const deck = {
  ScatterplotLayer: layer('point'), ColumnLayer: layer('column'), GeoJsonLayer: layer('polygon'),
  PathLayer: layer('path'), TripsLayer: layer('flow'),
  MapboxOverlay: class { constructor(p) { this.props = p; } setProps(p) { Object.assign(this.props, p); } },
};
const toggle = { enable() {}, disable() {} };
const canvas = { listeners: {}, addEventListener(type, fn) { (this.listeners[type] = this.listeners[type] || []).push(fn); }, removeEventListener() {} };
const maplibregl = {
  Map: class {
    constructor() { this.handlers = {}; this.doubleClickZoom = toggle; this.dragPan = toggle; this.dragRotate = toggle; this.boxZoom = toggle; }
    on(type, fn) { this.handlers[type] = fn; } off() {} addControl() {} removeControl() {} remove() {} resize() {} setStyle() {}
    getZoom() { return 12; } getBounds() { return null; } getStyle() { return { sources: {} }; } getPitch() { return 0; }
    getLayer() {} addLayer() {} jumpTo() {} fitBounds() {} flyTo() {}
    getCanvasContainer() { return canvas; } getCanvas() { return { getBoundingClientRect: () => ({ left: 0, top: 0 }) }; }
    project([lng, lat]) { return { x: lng * 1000, y: lat * 1000 }; }
    unproject([x, y]) { return { lng: x / 1000, lat: y / 1000 }; }
  },
};

const map = createMapView(grid, { container: el, libs: { deck, maplibregl }, geometry: { lat: 'lat', lng: 'lng' }, moveRows: true });
const seen = [];
let edits = 0;
grid.on('rows:changed', () => { edits += 1; });

map.draw.setMode('edit');
const mouse = (type, x, y) => dom.document.dispatchEvent({ type, clientX: x, clientY: y, button: 0, bubbles: true, target: null });
const press = (x, y) => { for (const fn of canvas.listeners.mousedown) fn({ button: 0, clientX: x, clientY: y, stopPropagation() {} }); };

press(900, 51880);                                  // on cabinet-7's point: it is taken, not the map
mouse('mousemove', 902, 51885);
mouse('mousemove', 905, 51890);                     // the point follows the pointer
mouse('mouseup', 905, 51890);                       // released: lat and lng are written together
const row = () => grid.rows.byKey('cabinet-7').data;
seen.push(`moved ${row().lat},${row().lng}`);
seen.push(edits === 1 ? 'one edit' : `${edits} edits`);

grid.edit.undo();                                   // one undo puts both cells back
seen.push(`undone ${row().lat},${row().lng}`);

map.destroy();
return seen.join(' | ');

Point size: a marker is held to a pixel cap when zoomed in, or set in pixels with radiusUnits

const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createHeadlessGrid } = await import('../packages/core/src/index.js');
const { createMapView } = await import('../packages/modules/mapview/index.js');

const dom = createTestDom();
const el = dom.document.createElement('div');
dom.root.appendChild(el);
const grid = createHeadlessGrid({
  rowKey: 'id',
  columns: [{ field: 'id' }, { field: 'lat', type: 'number' }, { field: 'lng', type: 'number' }],
  rows: [{ id: 'cabinet-7', lat: 51.88, lng: 0.9 }],
});

// Stand-ins for the page's deck.gl and MapLibre, as in the drawing example above.
const layer = (kind) => class { constructor(props) { this.props = props; this.kind = kind; } };
const deck = {
  ScatterplotLayer: layer('point'), ColumnLayer: layer('column'), GeoJsonLayer: layer('polygon'),
  PathLayer: layer('path'), TripsLayer: layer('flow'),
  MapboxOverlay: class { constructor(p) { this.props = p; } setProps(p) { Object.assign(this.props, p); } },
};
const maplibregl = {
  Map: class {
    on() {} off() {} addControl() {} removeControl() {} remove() {} resize() {} setStyle() {}
    getZoom() { return 12; } getBounds() { return null; } getStyle() { return { sources: {} }; }
    getLayer() {} addLayer() {} jumpTo() {} fitBounds() {} flyTo() {}
  },
};

const map = createMapView(grid, { container: el, libs: { deck, maplibregl }, geometry: { lat: 'lat', lng: 'lng' } });
const point = () => map.overlay.props.layers.find((l) => l.kind === 'point').props;
const seen = [];
let p = point();
seen.push(`${p.radiusUnits} cap ${p.radiusMaxPixels} min ${p.radiusMinPixels}`);   // 30 m, never past 24 px
map.update({ radiusMaxPixels: 10 });
p = point();
seen.push(`${p.radiusUnits} cap ${p.radiusMaxPixels}`);
map.update({ radiusMaxPixels: undefined, radiusUnits: 'pixels', radius: 8 });      // the same 8 px at every zoom
p = point();
seen.push(`${p.radiusUnits} ${p.getRadius(p.data[0])}`);

map.destroy();
return seen.join(' | ');

The map drives the grid: with viewportFilter the map's bounds are written as the grid's one bounding-box condition on every move

const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createHeadlessGrid } = await import('../packages/core/src/index.js');
const { createMapView } = await import('../packages/modules/mapview/index.js');

const dom = createTestDom({ width: 600, height: 400 });
const el = dom.document.createElement('div');
dom.root.appendChild(el);
const grid = createHeadlessGrid({
  rowKey: 'id',
  columns: [{ field: 'id' }, { field: 'lat', type: 'number' }, { field: 'lng', type: 'number' }],
  rows: [
    { id: 'london', lat: 51.5, lng: -0.1 },
    { id: 'paris', lat: 48.9, lng: 2.3 },
    { id: 'tokyo', lat: 35.7, lng: 139.7 },
  ],
});

// Stand-ins for the page's deck.gl and MapLibre. The map reports a box the
// example moves by hand; the real library fires `moveend` after a drag.
const layer = (kind) => class { constructor(props) { this.props = props; this.kind = kind; } };
const deck = {
  ScatterplotLayer: layer('point'), ColumnLayer: layer('column'), GeoJsonLayer: layer('polygon'),
  PathLayer: layer('path'), TripsLayer: layer('flow'),
  MapboxOverlay: class { constructor(p) { this.props = p; } setProps(p) { Object.assign(this.props, p); } },
};
const maplibregl = {
  Map: class {
    constructor() { this.box = [-180, -85, 180, 85]; this.handlers = {}; maplibregl.last = this; }
    on(t, fn) { (this.handlers[t] ??= new Set()).add(fn); } off(t, fn) { this.handlers[t]?.delete(fn); }
    fire(t) { for (const fn of [...(this.handlers[t] || [])]) fn(); }
    getBounds() { const [w, s, e, n] = this.box; return { getWest: () => w, getSouth: () => s, getEast: () => e, getNorth: () => n }; }
    fitBounds([[w, s], [e, n]]) { this.box = [w, s, e, n]; }
    addControl() {} removeControl() {} remove() {} resize() {} setStyle() {} getLayer() {} addLayer() {}
    getZoom() { return 5; } getStyle() { return { version: 8, sources: {}, layers: [] }; } jumpTo() {} flyTo() {}
  },
};

// `view` keeps the module from fitting the camera to the rows at bind, so the
// stand-in's own box is what gets written; `debounce: 0` writes on the move itself.
const map = createMapView(grid, {
  container: el, libs: { deck, maplibregl }, geometry: { lat: 'lat', lng: 'lng' },
  view: { zoom: 1 }, viewportFilter: { debounce: 0 },
});
const seen = [];
seen.push(String(grid.rows.matchCount()));                 // the whole world: every row

const theMap = maplibregl.last;
theMap.box = [-10, 35, 20, 60];                             // the map was dragged over Europe
theMap.fire('moveend');
await new Promise((r) => setTimeout(r, 30));
seen.push(String(grid.rows.matchCount()));                 // London and Paris

map.destroy();
seen.push(grid.filters.get() === null ? 'cleared' : 'left behind');   // destroy() prunes the condition
return seen.join(' | ');

Type reference

Generated from the type declarations, so it always matches the release. Each surface lists its properties, its methods and the events it raises as three tables; an option or value type lists its members once.

The map view

MapViewRoute

Routes assembled from ordinary rows: with `geometry: { lat, lng, route }` every row that has a place AND a non-blank value in the `by` column is one vertex of the route that value names, and each route is drawn as one line through its vertices in `order` (numbers as numbers, anything else as text; a blank last; rows with equal values in the order the grid shows them; no `order`: the grid's order). A row with a blank `by` is not a vertex: it stays a point (a cabinet, a splice) and is drawn as one. A vertex row is never also drawn as a point. A route's colour, width, dash and elevation are route-level: read from the route's first vertex row (in sequence order), or from `aggregate` across its rows.

PropertyTypeDescription
bystringThe column holding each vertex row's route id.
orderstringThe column holding each vertex's position in its route. (optional)
aggregate'first' | 'last' | 'min' | 'max'How a route-level style column is read across the route's rows: `first` (default), `last`, or `min` / `max` (numbers as numbers, anything else as text). An unknown value warns `mapview:route`. (optional)

MapViewDrawOptions

What {@link MapViewDraw.setMode} takes besides the mode itself.

PropertyTypeDescription
propertiesRecord<string, unknown>Properties merged onto every feature this mode finishes, until the mode changes again. Set `layer` to put the drawn shapes on a snap layer of their own (see `snap`). (optional)
snapMapViewDrawSnapSnap a new or moved vertex part 3) to the vertices, then the segments, of the features on `layers`, within `tolerance` pixels. A vertex snapped to a vertex takes that vertex's coordinates exactly. A layer id names a MapLibre layer of the page's own (a GeoJSON source given as an object snaps to its exact coordinates) or the drawn features whose `properties.layer` is that id. (optional)
constraintsMapViewDrawConstraintsRules a vertex must keep. A vertex that would break one is refused: it is not added or moved, a cue shows in the readout and `draw:refused` names the rule. (optional)

MapViewDrawSnap

Where a vertex snaps to: see {@link MapViewDrawOptions.snap}.

PropertyTypeDescription
layersstring[]The layer ids to snap to.
tolerancenumberHow close, in pixels, a vertex must be to a target to snap to it. Default 10, at most 100. (optional)

MapViewDrawConstraints

The rules {@link MapViewDrawOptions.constraints} sets, each optional.

PropertyTypeDescription
geometryTypesArray<'Point' | 'LineString' | 'Polygon'>The geometry types the mode may draw. A mode that would draw another is refused at its first vertex (`geometry-type`). `point` draws a `Point`, `line` a `LineString`, the rest a `Polygon`. (optional)
maxVerticesnumberThe most vertices a line or polygon may have (`max-vertices`). (optional)
minSegmentLengthnumberThe shortest segment, in metres, between neighbouring vertices (`min-segment-length`). (optional)
noSelfIntersectionbooleanRefuse a polygon vertex that would make the polygon cross itself (`self-intersection`). (optional)

MapViewDrawFeature

One shape the draw layer holds: a GeoJSON `Feature` with a generated `id`. `properties.shape` names the mode that drew it; `properties.readonly` (false for a shape the reader drew) is respected by part 2's selection and deletion. A circle's `properties` also carry `center` (`[lng, lat]`) and `radius` (metres); its `geometry` is the polygon that approximates it.

PropertyTypeDescription
type'Feature'Always `'Feature'`, as GeoJSON requires. (read-only)
idstringA generated id, unique within this map view's draw layer. (read-only)
geometryRecord<string, unknown>The GeoJSON geometry: a `Point`, `LineString` or `Polygon` (a circle and a rectangle are both a `Polygon`).
propertiesRecord<string, unknown> & { shape: MapViewDrawMode; readonly: boolean }`shape` names the drawing mode; `readonly` is respected by part 2's selection and deletion; a circle also carries `center` and `radius`.

MapViewDrawFeatureCollection

A `FeatureCollection` of {@link MapViewDrawFeature}.

PropertyTypeDescription
type'FeatureCollection'Always `'FeatureCollection'`, as GeoJSON requires. (read-only)
featuresMapViewDrawFeature[]The shapes.

MapViewDraw

Draw and edit shapes on the map view parts 1 and 2 of 3: create, then select and edit), in a layer above the data layers, styled from the map view's own theme roles. A click places a point, or adds a vertex to the line or polygon in progress; a double-click, or a click back on the first vertex, finishes it (a polygon's ring is always closed). A circle is dragged from its centre; a rectangle from corner to corner. Escape discards the shape in progress; so does switching `setMode` to a different mode. None of this changes the grid's rows. `setMode('edit')` selects and edits: a click selects a shape, Shift-click adds (or removes) one, a click on empty map or Escape clears, and Delete/Backspace deletes the selected shapes. A selected line or polygon shows a handle on each vertex and a smaller one on each segment's midpoint: drag a vertex to move it, drag a midpoint to insert a vertex, Alt-click (Option on macOS) a vertex, or click it and press Delete, to remove it (never below 2 vertices for a line or 3 for a polygon). Dragging a shape's body moves every selected shape. A circle has no vertex handles but its body moves. A shape with `properties.readonly` can be selected but shows no handles and is never moved or deleted. Ctrl/Cmd-Z and Ctrl/Cmd-Shift-Z undo and redo every create, edit, move and delete. Part 3 adds precision. `setMode`'s `snap` and `constraints` options snap a vertex to other features and refuse one that breaks a rule. While a shape is drawn or edited a readout beside the cursor gives its length and active segment (m / km), or its area and perimeter (m² / ha), in the grid's locale, kept inside the map. Touch works: tap to add a vertex, long-press to finish, drag a handle (a touch target of at least 24px); two fingers pan and zoom the map and never add a vertex.

MethodSignatureParametersReturnsDescription
setMode(mode: MapViewDrawControlMode | null, options?: MapViewDrawOptions): voidmode: MapViewDrawControlMode | null
options?: MapViewDrawOptions
voidSwitch what a click or a drag draws, at runtime; `null` turns drawing off. A shape already in progress under the old mode is discarded. A mode that is none of these leaves the mode unchanged.
getFeatures(): MapViewDrawFeatureCollection - MapViewDrawFeatureCollectionEvery finished shape, as a `FeatureCollection`.
setFeatures(geojson: MapViewDrawFeatureCollection | MapViewDrawFeature[]): voidgeojson: MapViewDrawFeatureCollection | MapViewDrawFeature[]voidReplace every finished shape with the features of a `FeatureCollection` (or a bare array of `Feature`s). A shape in progress is discarded. A feature with no `id` is given one; `properties.readonly` defaults to false.
clear(): void - voidRemove every finished shape. A shape in progress is discarded too. Starts a new undo history.
undo(): void - voidUndo the last create, edit, move or delete in this session (up to 100 steps). Fires no event of its own; read `getFeatures()`. `setFeatures` and `clear` start a new history.
redo(): void - voidRedo the change last undone, until a new change is made.

MapViewOptions

What {@link createMapView} takes.

PropertyTypeDescription
geometryMapViewGeometryWhere each row is placed. A row whose place is blank or cannot be read is skipped and counted in `provenance().skipped`. A name that is not a column of the grid: nothing is drawn and `mapview:geometry` warns.
containerHTMLElement | stringThe element (or a selector for it) the map fills. Given without a `mode`, the mode is `container`. (optional)
mode'container' | 'split' | 'tab' | 'popout'Where the map goes: `container` (the `container` element); `split` (the default without a container: the map beside the grid in the grid's own host, with a divider a pointer drags and the arrow keys move); `tab` (the grid and the map as two tabs); `popout` (a separate browser window on this page's libraries, or a floating panel when the popup is blocked). `split`, `tab` and `popout` need a grid made by `createGrid`. (optional)
layerMapViewLayer 'point' | 'column' | 'polygon' | 'path'The layer for the rows of one geometry: `point` (markers) or `column` (extruded columns) for points, `polygon` (areas, extruded with an `elevation`) for polygons, `path` (routes) for lines. Rows of another geometry keep their default: a point is a marker, or a column when an `elevation` is given; a polygon an area; a line a route. (optional)
elevationstring | numberA numeric column (or one number) for the height of columns and extruded areas, in metres. (optional)
elevationScalenumberA multiplier on `elevation`. Default 1. (optional)
colorMapViewColourHow rows are coloured. Default the grid theme's accent. (optional)
radiusstring | numberA marker's radius in metres: a numeric column or one number (default 30). A `column` layer draws every column at one radius, so only a number applies to it. (optional)
radiusMaxPixelsnumberThe largest a marker is drawn, in pixels, when `radiusUnits` is `'meters'` (the default 24): zoomed in, a marker stops growing at this size instead of covering buildings. Zoomed out it keeps its metres size, never under 3 pixels. Columns and areas are unaffected. (optional)
radiusUnits'meters' | 'pixels'What `radius` means for markers: `'meters'` (default, a size on the ground) or `'pixels'` (the same size on screen at every zoom; hit-testing, selection and `moveRows` work at that size, and an unset radius is 6 pixels). Columns always use metres. (optional)
widthstring | numberA route's width in pixels: a numeric column or one number. Default 3. A route is always drawn between 2 and 30 pixels wide whatever its width, wide enough to read at street level among extruded buildings, and drawn 2 m above the ground (4 m for points when routes are in view) so it does not z-fight the basemap at pitch. (optional)
dashMapViewDashDash lines by value or all alike; see {@link MapViewDash}. The legend shows each pattern the map names. (optional)
iconMapViewIconIcon markers for point rows; see {@link MapViewIcon}. (optional)
legendbooleanShow a legend in the map's box: a swatch for each colour the `color` rule maps and a sample line for each pattern `dash` names. Default off; `legend()` returns the same entries as data. (optional)
flowMapViewFlowAnimate a flow along the routes. Stops while the page is hidden, and is drawn still when the reader prefers reduced motion. (optional)
buildingsbooleanAdd 3D buildings from the basemap's OpenMapTiles `building` layer (`render_height`, `render_min_height`), coloured for the light or dark theme. Off by default. A style with no vector source warns `mapview:buildings`. (optional)
moveRowsbooleanLet rows placed by `geometry: { lat, lng }` be moved by dragging their point on the map in edit mode (`draw.setMode('edit')`). On release the new latitude and longitude are written through the grid's own editing path (`grid.edit.setCells`, origin `'user'`), so validation, `beforeEdit`, the grid's undo, its change events and a server write-back behave as for a typed cell edit; the two cells are one edit and one undo step. A refused edit puts the point back. A row whose latitude or longitude cell cannot be edited (read-only column, row or grid) shows no move cursor and cannot be dragged. Rows placed by a `geojson` or `path` column are not movable. Off by default: with it off a drag on a row pans the map. (optional)
basemapstring | Record<string, unknown>A MapLibre style URL or style object. Default OpenFreeMap's keyless positron, or its dark style for a dark theme. (optional)
viewMapViewCameraThe initial camera. Default: fitted to the drawn rows. (optional)
fit'once' | 'data' | falseWhen the map fits itself to its rows: `'once'` (the default) fits once, at first draw, and leaves the camera to the reader after that; `'data'` also refits, animated and debounced (250 ms), after every redraw whose set of row keys changed - a filter or quick search - unless the reader has panned or zoomed since the last automatic fit, which stops it until `fitToRows()` re-arms it; `false` never fits on its own. An empty row set never moves the map. (optional)
theme'light' | 'dark' | 'auto'`light` or `dark`; default the grid's own (`data-theme` above it, `auto` read from the reader's colour-scheme preference). (optional)
tooltipstring[] | falseThe columns the hover tooltip shows, each as the grid's own formatted cell text. Default the grid's first three visible columns that do not hold the place; `false` for no tooltip. A route's tooltip leads with its route id and shows its first row's cells. (optional)
libs{ deck?: unknown; maplibregl?: unknown }The page's deck.gl and MapLibre GL. Default the globals `deck` and `maplibregl` their UMD builds set. Either missing: the map is left empty and `mapview:libs` warns, naming which. (optional)
viewportFilterboolean | { debounce?: number }The map's view as a filter on the grid, the same contract `bindLeaflet` and `bindDeck` keep: written at bind time from the map's own bounds once its host has a size, so the grid and the KPIs agree with the layers from the first paint, and again after every `moveend` - a drag, the wheel, or the view's own `update({ view })` - debounced (default 150 ms), as ONE condition: a `withinBbox` on a `geojson`/`path` geometry column, or a `between` pair on `lon`/`lng`. A matching condition set from elsewhere fits the map to its box once, without being written back. Off by default. (optional)
viewportCapnumberOn a paged pushdown grid that holds only a window of its matching rows, the most rows the map fetches for its own current view, instead of drawing the grid's page: the grid's filters and quick search, plus a `withinBbox` on a `geometry` column or a `between` pair on `lon`/`lng` for the box once the reader has panned or zoomed, through the adapter's `execute`. A pan or zoom asks again (debounced, aborting the request it supersedes); the last drawing stays up until the answer lands. More rows than the cap fall inside the view: none are drawn, `mapview:over` warns naming the count and the cap, and `provenance().over` carries the same reason for a host that wants to show "N of M" itself. Default 20,000; as {@link ChartSpec.viewportCap}. Needs the pushdown source's own count to run in the engine: pass `aggregates: { default: 'engine' }` to `createPushdownSource` (DuckDB, ClickHouse, Elasticsearch and Splunk all support it). Left at the client-side default, the view's row count is worked out in the browser instead, so the map falls back to drawing the grid's own page - `provenance().computed` reads `'client'`, not `'engine'`, with no warning, because that is also what a grid holding every matching row looks like. `provenance().computed` is the one place to check which happened. const source = createPushdownSource({ adapter, aggregates: { default: 'engine' } }); const grid = createGrid(el, { rowKey: 'id', source, columns }); const map = createMapView(grid, { container: '#map', geometry: { lat: 'lat', lng: 'lng' }, viewportCap: 5000, }); map.provenance().computed; // 'engine' once the view has answered (optional)

MapViewProvenance

What a map view drew.

PropertyTypeDescription
drawnnumberThe rows drawn (every vertex row of a drawn route counts).
skippednumberThe rows the grid shows that have no usable place, so were not drawn; with `route`, also the vertex rows of a route skipped for having fewer than two usable vertices, so `drawn + skipped` is every matched row.
matchednumberThe rows the grid matched.
layersPartial<Record<MapViewLayer | 'icon', number>>The items drawn by each layer kind (a route is one path); `icon` counts the points drawn as icons, `point` the circles.
routesnumberWith `geometry.route`: the routes drawn. (optional)
routesSkippednumberWith `geometry.route`: the routes skipped for having fewer than two usable vertices. (optional)
routesRebuiltnumberWith `geometry.route`: the routes assembled from their rows on the last draw. A route none of whose vertex rows (or route-level style columns) changed is reused, so an edit, add, delete or filter of one vertex row assembles one route, not all of them. (optional)
computed'client' | 'engine'`client` when the grid held the rows, `engine` when a paged source's engine answered for the view.

MapViewEventPayloads

What each map view event carries.

PropertyTypeDescription
feature:click{ key: string | number; row: Record<string, unknown> | null; route?: string; keys?: Array<string | number> }A feature was clicked; its row is now selected in the grid. A route selects every one of its rows: `key` is its first row's key, `route` its id and `keys` all its rows' keys.
feature:hover{ key: string | number | null; row: Record<string, unknown> | null; lines: Array<{ column: string; title: string; text: string }> }The pointer moved onto a feature (`key` null when it left one); `lines` are the tooltip's.
draw{ provenance: MapViewProvenance }The layers were redrawn.
load{ map: unknown }The basemap style loaded (at first, and after a basemap or theme change).
closeRecord<string, never>The reader closed a popped-out map.
map:click{ lng: number; lat: number; features: unknown[] }A click anywhere on the map: where, and the data rows' features under the cursor, whether or not a draw mode is active.
draw:start{ mode: MapViewDrawMode; feature: MapViewDrawFeature }A shape started: a point's own click, the first vertex of a line or polygon, or a circle or rectangle's drag beginning.
draw:change{ mode: MapViewDrawMode; feature: MapViewDrawFeature }The shape in progress changed: a vertex added, or the drag moved.
draw:finish{ feature: MapViewDrawFeature }A shape finished: the feature now held by `draw.getFeatures()`.
draw:refused{ mode: MapViewDrawControlMode; rule: MapViewDrawRule; position: [number, number] }A vertex was refused part 3) for breaking a rule of `setMode`'s `constraints`: the mode, the rule, and where the vertex would have gone.
edit:change{ id: string | number; geometry: Record<string, unknown>; feature: MapViewDrawFeature }A shape was reshaped or moved in edit mode, fired on release: its id and its new geometry. A move of several selected shapes fires one per shape; a vertex removed fires one too.
feature:select{ ids: Array<string | number> }The selection changed in edit mode: the ids now selected.
feature:delete{ ids: Array<string | number> }Shapes were deleted in edit mode: their ids. Undo restores them silently.

MapView

A live map view of a grid.

Properties
PropertyTypeDescription
elementHTMLElement | nullThe map view's own element. (read-only)
mapunknownThe MapLibre map; null when the map could not be built. (read-only)
overlayunknowndeck.gl's `MapboxOverlay` on it; null when the map could not be built. (read-only)
drawMapViewDrawDraw and edit the map view's own shapes; see {@link MapViewDraw}. (read-only)
Methods
MethodSignatureParametersReturnsDescription
getMap(): unknown - unknownThe MapLibre map: the escape hatch for anything this module does not wrap. Same object as `.map`.
update(options?: Partial<MapViewOptions>): voidoptions?: Partial<MapViewOptions>voidChange options and redraw now: `basemap` and `theme` restyle the map, `buildings` adds or removes them, `view` moves the camera, and `geometry` re-reads every row's place.
flyTo(keys: string | number | Array<string | number>): voidkeys: string | number | Array<string | number>voidFly to one row, or fit the map to several.
fitToRows(): void - voidFit the map to the rows it is drawing now, and arm the automatic fit again for `fit: 'data'` after the reader has panned or zoomed it.
setLayer(layer: MapViewLayer): voidlayer: MapViewLayervoidDraw the rows of one geometry with this layer kind.
provenance(): MapViewProvenance - MapViewProvenanceWhat the map drew last: rows drawn, skipped and matched, and per layer.
layers(): unknown[] - unknown[]The deck.gl layers last handed to the map, in draw order: areas, routes, columns, points, icons.
legend(): { colours: Array<{ label: string; colour: number[] }>; dashes: Array<{ label: string; dash: [number, number] | null }>; sections: Array<{ field: string | null; title: string; merged: boolean; entries: Array<{ label: string; colour: number[] | null; dash: [number, number] | null; line: boolean }>; }>; } - { colours: Array<{ label: string; colour: number[] }>; dashes: Array<{ label: string; dash: [number, number] | null }>; sections: Array<{ field: string | null; title: string; merged: boolean; entries: Array<{ label: string; colour: number[] | null; dash: [number, number] | null; line: boolean }>; }>; }What the legend shows, as data. `sections` is what is drawn: one merged section when the colour and dash rules key on the same field (an entry per value, `line` true for a value drawn as a line, its sample in that value's colour and `dash`; false for a point-only value, a square), else one section per rule titled by its field's header. `colours` and `dashes` are the two rules' own entries (`null` dash is solid).
on(name: MapViewEventName, fn: (event: MapViewEventPayloads[MapViewEventName]) => void): () => voidname: MapViewEventName
fn: (event: MapViewEventPayloads[MapViewEventName]) => void
() => voidListen for an event; returns the unsubscribe. An unknown name warns `mapview:event:<name>`.
off(name: MapViewEventName, fn: (event: MapViewEventPayloads[MapViewEventName]) => void): voidname: MapViewEventName
fn: (event: MapViewEventPayloads[MapViewEventName]) => void
voidStop listening for an event.
destroy(): void - voidRemove the map, its layers and every listener, and put the grid back where it was.
Events
EventWhenPayloadCancellable
feature:click{ key: string | number; row: Record<string, unknown> | null; route?: string; keys?: Array<string | number> } -
feature:hover{ key: string | number | null; row: Record<string, unknown> | null; lines: Array<{ column: string; title: string; text: string }> } -
draw{ provenance: MapViewProvenance }no
load{ map: unknown } -
closeRecord<string, never> -
map:click{ lng: number; lat: number; features: unknown[] } -
draw:start{ mode: MapViewDrawMode; feature: MapViewDrawFeature }no
draw:change{ mode: MapViewDrawMode; feature: MapViewDrawFeature }no
draw:finish{ feature: MapViewDrawFeature }no
edit:change{ id: string | number; geometry: Record<string, unknown>; feature: MapViewDrawFeature }no
feature:select{ ids: Array<string | number> } -
feature:delete{ ids: Array<string | number> } -
draw:refused{ mode: MapViewDrawControlMode; rule: MapViewDrawRule; position: [number, number] } -