Skip to content

Types

All types are exported as TypeScript type-only exports from @sindicum/libre-draw.

ts
import type {
  LibreDrawFeature,
  FeatureCollection,
  PointGeometry,
  LineStringGeometry,
  PolygonGeometry,
  LibreDrawGeometry,
  Position,
  FeatureProperties,
  LibreDrawOptions,
  KeyboardOptions,
  SnapConfig,
  ToolbarOptions,
  ToolbarPosition,
  ToolbarControls,
  StyleConfig,
  PartialStyleConfig,
  FillStyle,
  OutlineStyle,
  VertexStyle,
  PreviewStyle,
  EditVertexStyle,
  MidpointStyle,
  PointStyle,
  ModeName,
  Action,
  ActionType,
  FeatureStoreInterface,
  NormalizedInputEvent,
  InputType,
  Locale,
  Messages,
  OperationResult,
  OperationSuccess,
  OperationFailure,
  AddFeaturesOptions,
  AddFeatureResult,
  FeatureValidationResult,
  UpdateFeaturePatch,
  UpdateFeatureFailReason,
  RotateFailReason,
  EdgeRef,
  SplitOperationFailReason,
  SetbackOperationFailReason,
  UnionOperationFailReason,
} from '@sindicum/libre-draw';

Event payload types (CreateEvent, LibreDrawEventMap, EventOrigin, the *FailReason unions, …) are documented on the Events page and exported the same way. Runtime values (LibreDrawError, DEFAULT_STYLE_CONFIG, mergeStyleConfig, the *Action classes) use a plain import.


Feature Types

Position

A geographic coordinate pair [longitude, latitude].

ts
type Position = [number, number];
IndexRangeDescription
0-180 to 180Longitude
1-90 to 90Latitude

PointGeometry

GeoJSON Point geometry.

ts
interface PointGeometry {
  type: 'Point';
  coordinates: Position;
}
PropertyTypeDescription
type'Point'Always 'Point'
coordinatesPositionA single [longitude, latitude] coordinate

LineStringGeometry

GeoJSON LineString geometry.

ts
interface LineStringGeometry {
  type: 'LineString';
  coordinates: Position[];
}
PropertyTypeDescription
type'LineString'Always 'LineString'
coordinatesPosition[]Array of [longitude, latitude] coordinates. Minimum 2 positions required.

PolygonGeometry

GeoJSON Polygon geometry.

ts
interface PolygonGeometry {
  type: 'Polygon';
  coordinates: Position[][];
}
PropertyTypeDescription
type'Polygon'Always 'Polygon'
coordinatesPosition[][]Array of linear rings. The first ring is the outer boundary. Each ring must be closed (first position === last position).

LibreDrawGeometry

Union of supported GeoJSON geometry types.

ts
type LibreDrawGeometry = PointGeometry | LineStringGeometry | PolygonGeometry;

FeatureProperties

Arbitrary key-value properties attached to a feature.

ts
interface FeatureProperties {
  [key: string]: unknown;
}

LibreDrawFeature

A GeoJSON Feature used by LibreDraw. Supports Point, LineString, and Polygon geometry types.

ts
interface LibreDrawFeature {
  id: string;
  type: 'Feature';
  geometry: LibreDrawGeometry;
  properties: FeatureProperties;
}
PropertyTypeDescription
idstringUUID v4 unique identifier
type'Feature'Always 'Feature'
geometryLibreDrawGeometryPoint, LineString, or Polygon geometry
propertiesFeaturePropertiesArbitrary metadata

FeatureCollection

A GeoJSON FeatureCollection containing LibreDraw features (points, lines, and polygons). Returned by toGeoJSON().

ts
interface FeatureCollection {
  type: 'FeatureCollection';
  features: LibreDrawFeature[];
}
PropertyTypeDescription
type'FeatureCollection'Always 'FeatureCollection'
featuresLibreDrawFeature[]Array of point, line, and polygon features

Configuration Types

LibreDrawOptions

Options for creating a LibreDraw instance.

ts
interface LibreDrawOptions {
  toolbar?: boolean | ToolbarOptions;
  keyboard?: boolean | KeyboardOptions;
  historyLimit?: number;
  style?: PartialStyleConfig;
  snap?: boolean | SnapConfig;
  locale?: Locale;
  messages?: Partial<Messages>;
}
PropertyTypeDefaultDescription
toolbarboolean | ToolbarOptionstrueWhether to show the toolbar, or toolbar configuration. Set to false for headless mode.
keyboardboolean | KeyboardOptionstrueWhether to enable keyboard shortcuts, or shortcut configuration. See KeyboardOptions.
historyLimitnumber100Maximum number of undo/redo history entries
stylePartialStyleConfigdefault stylePartial overrides for map layer styling (fill / outline / preview / edit handles / midpoints / points).
snapboolean | SnapConfigtrueWhether to enable snapping, or snap configuration (SnapConfig). Set to false to disable.
localeLocale'en'Language of the toolbar and its popups. Throws LibreDrawError for an unknown value.
messagesPartial<Messages>{}Overrides for individual UI strings, merged onto the selected locale. See Messages.

SnapConfig

Configuration for vertex snapping while drawing and editing.

ts
interface SnapConfig {
  enabled?: boolean;
  threshold?: number;
}
PropertyTypeDefaultDescription
enabledbooleantrueWhether snapping is enabled
thresholdnumber10Snap distance in pixels (values below 1 are clamped to 1)

KeyboardOptions

Configuration for keyboard shortcuts. Shortcuts only fire while the map has focus (clicking the map focuses it). See the shortcut list for the keys.

ts
interface KeyboardOptions {
  undoRedo?: boolean;
}
PropertyTypeDefaultDescription
undoRedobooleantrueWhether Ctrl/Cmd+Z (undo), Ctrl/Cmd+Shift+Z and Ctrl+Y (redo) are handled. Escape / Delete handling inside modes is not affected.

ToolbarOptions

Configuration options for the toolbar.

ts
interface ToolbarOptions {
  position?: ToolbarPosition;
  controls?: ToolbarControls;
}
PropertyTypeDefaultDescription
positionToolbarPosition'top-right'Where to place the toolbar on the map
controlsToolbarControlsAll trueWhich buttons to display

ToolbarPosition

Position of the toolbar control on the map.

ts
type ToolbarPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';

ToolbarControls

Configuration for which toolbar controls to display.

ts
interface ToolbarControls {
  drawPoint?: boolean;
  drawLine?: boolean;
  drawPolygon?: boolean;
  drawRectangle?: boolean;
  select?: boolean;
  split?: boolean;
  setback?: boolean;
  union?: boolean;
  rotate?: boolean;
  settings?: boolean;
  delete?: boolean;
  undo?: boolean;
  redo?: boolean;
}
PropertyTypeDefaultDescription
drawPointbooleantrueShow draw-point mode toggle button
drawLinebooleantrueShow draw-line mode toggle button
drawPolygonbooleantrueShow draw-polygon mode toggle button
drawRectanglebooleantrueShow draw-rectangle mode toggle button
selectbooleantrueShow select mode toggle button
splitbooleantrueShow split mode toggle button
setbackbooleantrueShow setback mode toggle button and distance input
unionbooleantrueShow union mode toggle button
rotatebooleantrueShow rotate mode toggle button and angle input
settingsbooleantrueShow style settings button and panel
deletebooleantrueShow delete button
undobooleantrueShow undo button
redobooleantrueShow redo button

Localization Types

Locale

Bundled UI languages.

ts
type Locale = 'en' | 'ja';

Messages

Every user-visible string of the toolbar and its popups. All keys are required in the bundled tables; pass a Partial<Messages> as messages to override a subset.

ts
interface Messages {
  // Toolbar button titles (also used as aria-label)
  toolbarDrawPoint: string;
  toolbarDrawLine: string;
  toolbarDrawPolygon: string;
  toolbarDrawRectangle: string;
  toolbarSelect: string;
  toolbarSplit: string;
  toolbarUnion: string;
  toolbarSetback: string;
  toolbarRotate: string;
  toolbarSettings: string;
  toolbarDelete: string;
  toolbarUndo: string;
  toolbarRedo: string;
  // Setback distance popup
  setbackDistanceInput: string; // aria-label of the field
  setbackExecute: string; // visible text of the execute button
  setbackExecuteLabel: string; // aria-label of the execute button
  // Rotation angle popup
  rotateAngleInput: string;
  rotateExecute: string;
  rotateExecuteLabel: string;
  // Style settings panel
  styleFeatureSection: string;
  styleSelectedSection: string;
  styleGuideSection: string;
  styleOutlineColor: string;
  styleOutlineWidth: string;
  styleFillColor: string;
  styleFillOpacity: string;
  stylePointColor: string;
  stylePointRadius: string;
  stylePointHoverColor: string;
  styleVertexColor: string;
  styleVertexRadius: string;
  styleMidpointColor: string;
  styleMidpointRadius: string;
  styleVertexHoverColor: string;
  styleSelectedOutlineColor: string;
  styleSelectedFillColor: string;
  styleSelectedFillOpacity: string;
  stylePreviewColor: string;
  stylePreviewWidth: string;
}
ts
// Japanese UI with one label changed
const draw = new LibreDraw(map, {
  locale: 'ja',
  messages: { setbackExecute: '適用' },
});

Mode Types

ModeName

The available drawing mode names.

ts
type ModeName =
  | 'idle'
  | 'draw-point'
  | 'draw-line'
  | 'draw-polygon'
  | 'draw-rectangle'
  | 'select'
  | 'split'
  | 'setback'
  | 'union'
  | 'rotate';
ValueDescription
'idle'No drawing interaction. Map behaves normally.
'draw-point'Place point features by clicking/tapping.
'draw-line'Create lines by clicking/tapping vertices, click the last one to finalize.
'draw-polygon'Create polygons by clicking/tapping vertices, click the first or last one.
'draw-rectangle'Create an axis-aligned rectangle by clicking/tapping two opposite corners.
'select'Select and edit existing features (points, lines, and polygons).
'split'Split a polygon into two polygons with a two-point line.
'union'Merge two touching or overlapping polygons into one by clicking them in turn.
'setback'Apply inward edge setback with distance input and preview.
'rotate'Rotate a polygon or line around its center by dragging or angle input.

Action Types

ActionType

The type of history action.

ts
type ActionType = 'create' | 'update' | 'delete' | 'split' | 'setback' | 'union' | 'batch';

'batch' is used by BatchAction, which groups several actions into one history step (for example, one addFeatures() call).


Action

A reversible action that can be applied and reverted on a FeatureStore.

ts
interface Action {
  type: ActionType;
  apply(store: FeatureStoreInterface): void;
  revert(store: FeatureStoreInterface): void;
}
PropertyTypeDescription
typeActionTypeThe kind of action
apply(store) => voidApply the action to the store
revert(store) => voidRevert the action from the store

BatchAction

An Action that groups multiple child actions into a single undo/redo step. apply runs the children in order; revert runs them in reverse order. Exported so that history-aware integrations can recognise batched steps.

ts
class BatchAction implements Action {
  readonly type: 'batch';
  readonly actions: readonly Action[];
  constructor(actions: readonly Action[]);
}

Action classes

The other multi-feature steps are exported as classes too, so a history-aware integration can inspect what an undo or redo will touch. Their fields mirror the corresponding event payloads.

ts
class SplitAction implements Action {
  readonly type: 'split';
  readonly originalFeature: LibreDrawFeature;
  readonly featureA: LibreDrawFeature;
  readonly featureB: LibreDrawFeature;
}

class SetbackAction implements Action {
  readonly type: 'setback';
  readonly originalFeature: LibreDrawFeature;
  readonly resultFeature: LibreDrawFeature;
  readonly edgeIndex: number;
  readonly distance: number;
}

class UnionAction implements Action {
  readonly type: 'union';
  readonly featureA: LibreDrawFeature;
  readonly featureB: LibreDrawFeature;
  readonly resultFeature: LibreDrawFeature;
}

FeatureStoreInterface

Minimal interface for the FeatureStore used by actions. This avoids circular imports between types and core modules.

ts
interface FeatureStoreInterface {
  add(feature: LibreDrawFeature): void;
  update(id: string, feature: LibreDrawFeature): void;
  remove(id: string): void;
  getById(id: string): LibreDrawFeature | undefined;
}

Operation Result Types

Structured outcomes returned by the public API. None of them is thrown; narrow on the discriminant (ok / valid) to read the rest.

OperationResult

The result of an editing operation (updateFeature, rotate, split, setback, and union).

ts
interface OperationSuccess {
  ok: true;
  created: LibreDrawFeature[];
  updated: LibreDrawFeature[];
  deleted: LibreDrawFeature[];
}

interface OperationFailure {
  ok: false;
  reason: string;
}

type OperationResult = OperationSuccess | OperationFailure;
PropertyTypeDescription
okbooleantrue when the store changed, false when the operation was rejected and nothing changed
createdLibreDrawFeature[]Features added by the operation (empty when none)
updatedLibreDrawFeature[]Features whose geometry or properties changed, as they are after the change (empty when none)
deletedLibreDrawFeature[]Features removed by the operation (empty when none)
reasonstringWhy the operation was rejected: an operation's failure code (e.g. 'has-holes') or a validation message

All three arrays are always present on success, so a caller can read "what appeared, what changed, what disappeared" without knowing which operation ran.

ts
const result = draw.rotate(id, 90);
if (!result.ok) {
  console.warn(result.reason);
  return;
}
result.updated.forEach(save);

AddFeaturesOptions

Options for addFeatures().

ts
interface AddFeaturesOptions {
  strict?: boolean;
}
PropertyTypeDefaultDescription
strictbooleantruetrue: one invalid feature makes the call throw and nothing is added. false: invalid features are reported in the result and only the valid ones are added.

AddFeatureResult

One entry per input feature of addFeatures(), in input order.

ts
type AddFeatureResult = { valid: true; id: string } | { valid: false; id?: string; reason: string };
PropertyTypeDescription
validbooleanWhether the feature was added
idstringValid: the id the feature has in the store (generated when the input had none). Invalid: the input id, if it had one
reasonstringInvalid only: the same message the strict mode would have thrown

FeatureValidationResult

Returned by validateFeature().

ts
type FeatureValidationResult =
  | { valid: true; feature: LibreDrawFeature }
  | { valid: false; reason: string };
PropertyTypeDescription
validbooleanWhether the object would be accepted by addFeatures()
featureLibreDrawFeatureValid only: a normalized copy (ids and properties as they would be stored)
reasonstringInvalid only: the rejection message

UpdateFeaturePatch

What updateFeature() replaces on a feature. Each field is a full replacement; omit a field to keep it.

ts
interface UpdateFeaturePatch {
  geometry?: LibreDrawGeometry;
  properties?: FeatureProperties;
}
PropertyTypeDescription
geometryLibreDrawGeometryNew geometry. Must have the same type as the current geometry
propertiesFeaturePropertiesNew properties object. Replaces the old one entirely (no merge)

UpdateFeatureFailReason

Failure codes of updateFeature(). A geometry that fails validation reports the validation message instead of a code.

ts
type UpdateFeatureFailReason = 'not-found' | 'geometry-type-mismatch' | 'empty-patch';
ValueMeaning
'not-found'No feature has that id
'geometry-type-mismatch'The patch would change the geometry type
'empty-patch'Neither geometry nor properties was given

RotateFailReason

Failure codes of rotate(). A rotated shape that fails validation (it would leave the coordinate range near the antimeridian or the poles) reports the validation message instead of a code.

ts
type RotateFailReason = 'not-found' | 'not-rotatable' | 'no-rotation';
ValueMeaning
'not-found'No feature has that id
'not-rotatable'The feature is a Point
'no-rotation'The angle is 0, a multiple of 360, or not finite, so nothing would change

EdgeRef

A reference to one edge of a Polygon, used by setback().

ts
interface EdgeRef {
  ring?: number;
  index: number;
}
PropertyTypeDescription
ringnumberRing index; 0 (the outer ring) when omitted. Inner rings cannot be edited yet, so any other value is rejected with 'has-holes'
indexnumberEdge index within the ring, counted without the closing position: edge i runs from vertex i to vertex i + 1, and the last edge returns to vertex 0. Same numbering as SetbackEvent.edgeIndex

SplitOperationFailReason

Failure codes of split(). The geometric codes are the SplitFailReason values of the splitfailed event, which is emitted alongside; the argument errors below emit no event. A result that fails validation reports the validation message instead of a code.

ts
type SplitOperationFailReason = 'not-found' | 'not-splittable' | SplitFailReason;
ValueMeaning
'not-found'No feature has that id
'not-splittable'The feature is a Point

SetbackOperationFailReason

Failure codes of setback(). 'has-holes' and 'invalid-split' are the SetbackFailReason values of the setbackfailed event, which is emitted alongside; the argument errors below emit no event.

ts
type SetbackOperationFailReason =
  | 'not-found'
  | 'not-polygon'
  | 'invalid-edge'
  | 'invalid-distance'
  | SetbackFailReason;
ValueMeaning
'not-found'No feature has that id
'not-polygon'The feature is not a Polygon
'invalid-edge'edge.index is not an integer in [0, vertexCount)
'invalid-distance'The distance is not a finite number greater than zero

UnionOperationFailReason

Failure codes of union(). The geometric codes are the UnionFailReason values of the unionfailed event, which is emitted alongside; the argument errors below emit no event.

ts
type UnionOperationFailReason = 'not-found' | 'unsupported-count' | UnionFailReason;
ValueMeaning
'not-found'One of the ids has no feature
'unsupported-count'ids does not name exactly two distinct features

Input Types

InputType

The type of input device that generated an event.

ts
type InputType = 'mouse' | 'touch';

NormalizedInputEvent

A normalized input event shared across mouse and touch handlers.

ts
interface NormalizedInputEvent {
  lngLat: { lng: number; lat: number };
  point: { x: number; y: number };
  originalEvent: MouseEvent | TouchEvent;
  inputType: InputType;
}
PropertyTypeDescription
lngLat{ lng: number; lat: number }The geographic coordinate at the event location
point{ x: number; y: number }The screen pixel coordinate at the event location
originalEventMouseEvent | TouchEventThe original DOM event
inputTypeInputTypeThe input device type that generated this event

Style Types

StyleConfig

Full render style configuration. Returned by getStyle().

ts
interface StyleConfig {
  fill: FillStyle;
  outline: OutlineStyle;
  /** @deprecated Has no effect; will be removed in v1.0. */
  vertex: VertexStyle;
  preview: PreviewStyle;
  editVertex: EditVertexStyle;
  midpoint: MidpointStyle;
  point: PointStyle;
}
PropertyTypeDescription
fillFillStylePolygon fill rendering
outlineOutlineStylePolygon/line outline rendering
vertexVertexStyleDeprecated. Has no effect
previewPreviewStyleDraw preview / guide line
editVertexEditVertexStyleEdit vertex handles (selected features)
midpointMidpointStyleMidpoint handles (selected features)
pointPointStylePoint geometry features

PartialStyleConfig

Partial style overrides accepted by the constructor style option and setStyle(). All sections and properties are optional — unset values retain their current or default value.

ts
interface PartialStyleConfig {
  fill?: Partial<FillStyle>;
  outline?: Partial<OutlineStyle>;
  /** @deprecated Has no effect; will be removed in v1.0. */
  vertex?: Partial<VertexStyle>;
  preview?: Partial<PreviewStyle>;
  editVertex?: Partial<EditVertexStyle>;
  midpoint?: Partial<MidpointStyle>;
  point?: Partial<PointStyle>;
}

FillStyle

Style for polygon fill rendering.

ts
interface FillStyle {
  color: string;
  opacity: number;
  selectedColor: string;
  selectedOpacity: number;
}
PropertyTypeDefaultDescription
colorstring'#3bb2d0'Fill color
opacitynumber0.2Fill opacity (0–1)
selectedColorstring'#fbb03b'Fill color when selected
selectedOpacitynumber0.4Fill opacity when selected

OutlineStyle

Style for polygon/line outline rendering.

ts
interface OutlineStyle {
  color: string;
  width: number;
  selectedColor: string;
}
PropertyTypeDefaultDescription
colorstring'#3bb2d0'Line color
widthnumber2Line width in pixels
selectedColorstring'#fbb03b'Line color when selected

VertexStyle

Deprecated

vertex has no effect. The layer it styled was removed in v0.9.1 (it had rendered nothing since v0.5.2). The option is still accepted so existing code keeps compiling, and will be removed in v1.0. Draft and edit vertex markers are styled by EditVertexStyle.

ts
interface VertexStyle {
  color: string;
  strokeColor: string;
  strokeWidth: number;
  radius: number;
}
PropertyTypeDefaultDescription
colorstring'#ffffff'Vertex fill color
strokeColorstring'#3bb2d0'Vertex stroke color
strokeWidthnumber2Vertex stroke width
radiusnumber4Vertex radius in pixels

PreviewStyle

Style for draw preview and guide lines (split, setback).

ts
interface PreviewStyle {
  color: string;
  width: number;
  dasharray: number[];
}
PropertyTypeDefaultDescription
colorstring'#3bb2d0'Dash line color
widthnumber2Dash line width
dasharraynumber[][2, 2]Dash pattern

EditVertexStyle

Style for edit vertex handles on selected features.

ts
interface EditVertexStyle {
  color: string;
  strokeColor: string;
  strokeWidth: number;
  radius: number;
  highlightedColor: string;
  highlightedStrokeColor: string;
  highlightedRadius: number;
}
PropertyTypeDefaultDescription
colorstring'#ffffff'Handle fill color
strokeColorstring'#3bb2d0'Handle stroke color
strokeWidthnumber2Handle stroke width
radiusnumber5Handle radius
highlightedColorstring'#ff4444'Hover/highlight fill color
highlightedStrokeColorstring'#cc0000'Hover/highlight stroke color
highlightedRadiusnumber7Hover/highlight radius

MidpointStyle

Style for midpoint handles on selected features.

ts
interface MidpointStyle {
  color: string;
  opacity: number;
  radius: number;
}
PropertyTypeDefaultDescription
colorstring'#3bb2d0'Midpoint fill color
opacitynumber0.6Midpoint opacity
radiusnumber4Midpoint radius

PointStyle

Style for Point geometry features.

ts
interface PointStyle {
  color: string;
  radius: number;
  selectedColor: string;
  selectedRadius: number;
  hoverColor: string;
  strokeColor: string;
  strokeWidth: number;
}
PropertyTypeDefaultDescription
colorstring'#3bb2d0'Point fill color
radiusnumber6Point radius in pixels
selectedColorstring'#fbb03b'Point color when selected
selectedRadiusnumber8Point radius when selected
hoverColorstring'#fbb03b'Point color on mouse hover
strokeColorstring'#3bb2d0'Point stroke color
strokeWidthnumber2Point stroke width

Style defaults and merging

Runtime exports for working with styles outside a LibreDraw instance.

ts
const DEFAULT_STYLE_CONFIG: StyleConfig;
function mergeStyleConfig(overrides?: PartialStyleConfig, base?: StyleConfig): StyleConfig;

DEFAULT_STYLE_CONFIG is the built-in style whose values are listed in the tables above. mergeStyleConfig returns a new StyleConfig with overrides applied on top of base (default: DEFAULT_STYLE_CONFIG); neither argument is mutated. The constructor uses it with the defaults for the style option, and setStyle() passes the current style as base so partial updates accumulate.


Error Class

LibreDrawError

Base error class for all LibreDraw errors. Extends the native Error class.

ts
class LibreDrawError extends Error {
  constructor(message: string);
  name: 'LibreDrawError';
}

Thrown when:

  • A method is called on a destroyed instance
  • Invalid GeoJSON is passed to setFeatures or addFeatures
  • addFeatures receives a feature whose id already exists in the store
  • selectFeature is called with a non-existent feature ID
  • Invalid polygon geometry (self-intersecting, out-of-bounds coordinates, etc.)
  • The constructor receives a locale that is not 'en' or 'ja'
ts
import { LibreDrawError } from '@sindicum/libre-draw';

try {
  draw.setFeatures({ invalid: 'data' });
} catch (e) {
  if (e instanceof LibreDrawError) {
    console.error('LibreDraw error:', e.message);
  }
}

Released under the MIT License.