### Install Dependencies and Run Dev App
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/README.md
Install project dependencies using pnpm and run the development application with either the MapLibre or Mapbox adapter.
```shell
pnpm install --frozen-lockfile
pnpm run dev:maplibre
pnpm run dev:mapbox
```
--------------------------------
### Install Mapbox-Geoman
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/packages/mapbox/README.md
Install the Mapbox-Geoman package using npm.
```shell
npm install @geoman-io/mapbox-geoman-free
```
--------------------------------
### Enable Snap Guides
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/08-modes-draw-edit-helper.md
Enable the `snap_guides` helper to visualize snap guidance lines during geometry creation or editing.
```typescript
await geoman.enableMode('helper', 'snap_guides');
```
--------------------------------
### Handle Marker Movement Events
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/04-events-system.md
This example demonstrates how to track the movement of feature markers (vertices or handles). It calculates the distance moved using the start and end coordinates provided in the event.
```typescript
map.on('gm:edit', (event) => {
if (event.action === 'marker_move') {
const distance = haversineDistance(event.lngLatStart, event.lngLatEnd);
console.log(`Moved ${distance}km`);
}
});
```
--------------------------------
### Instantiate ShapeMarkersHelper
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/06-utilities.md
Example of how to instantiate the ShapeMarkersHelper. Ensure the 'geoman' instance is available.
```typescript
const helper = new ShapeMarkersHelper(geoman);
```
--------------------------------
### Install Maplibre Geoman Free Version
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/README.md
Use these commands to install the free version of Maplibre Geoman.
```shell
# install maplibre free version
npm install @geoman-io/maplibre-geoman-free
```
```shell
# install mapbox free version
npm install @geoman-io/mapbox-geoman-free
```
--------------------------------
### React Integration Example
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/09-quick-start-guide.md
Integrate MapLibre Geoman into a React application. This example shows how to initialize the map and Geoman, enable drawing, and handle cleanup.
```typescript
import { useEffect, useRef, useState } from "react";
import ml from "maplibre-gl";
import { Geoman } from "@geoman-io/maplibre-geoman-free";
import "maplibre-gl/dist/maplibre-gl.css";
import "@geoman-io/maplibre-geoman-free/dist/maplibre-geoman.css";
export function MapComponent() {
const mapContainer = useRef(null);
const map = useRef(null);
const geoman = useRef(null);
const [isReady, setIsReady] = useState(false);
useEffect(() => {
if (!mapContainer.current) return;
// Initialize map
map.current = new ml.Map({
container: mapContainer.current,
style: {
version: 8,
sources: { osm: { type: "raster", tiles: [...] } },
layers: []
},
center: [0, 51],
zoom: 5
});
// Initialize Geoman
geoman.current = new Geoman(map.current);
const handleGeomanLoaded = async () => {
setIsReady(true);
await geoman.current.enableDraw("polygon");
};
map.current.on("gm:loaded", handleGeomanLoaded);
// Cleanup on unmount
return async () => {
if (geoman.current) {
await geoman.current.destroy();
}
map.current?.remove();
};
}, []);
return (
{isReady &&
Geoman is ready! Draw on the map.
}
);
}
```
--------------------------------
### Install MapLibre Geoman (MapLibre GL JS)
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/09-quick-start-guide.md
Install the MapLibre Geoman free version and MapLibre GL JS using npm. This is for projects using MapLibre GL JS.
```bash
npm install @geoman-io/maplibre-geoman-free maplibre-gl
```
--------------------------------
### Install MapLibre Geoman (Mapbox GL JS)
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/09-quick-start-guide.md
Install the MapLibre Geoman free version and Mapbox GL JS using npm. This is for projects using Mapbox GL JS.
```bash
npm install @geoman-io/mapbox-geoman-free mapbox-gl
```
--------------------------------
### Basic Geoman Setup with MapLibre
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/README.md
Initialize a MapLibre map and the Geoman instance. Enables drawing a polygon after the map and Geoman are loaded.
```typescript
import ml from "maplibre-gl";
import { Geoman } from "@geoman-io/maplibre-geoman-free";
const map = new ml.Map({ /* ... */ });
const geoman = new Geoman(map);
map.on('gm:loaded', async () => {
await geoman.enableDraw('polygon');
});
```
--------------------------------
### Install Maplibre Geoman Pro Version
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/README.md
After configuring your .npmrc file, use this command to install the pro version of Maplibre Geoman.
```shell
# install pro version
npm install @geoman-io/maplibre-geoman-pro
```
--------------------------------
### Install Maplibre-Geoman
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/packages/maplibre/README.md
Install the Maplibre-Geoman package using npm. This command adds the library to your project's dependencies.
```shell
npm install @geoman-io/maplibre-geoman-free
```
--------------------------------
### Basic Geoman Setup with Options
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/03-gm-options.md
Initialize Geoman with custom settings and control configurations. Use this to enable/disable specific drawing tools or adjust UI positioning and behavior.
```typescript
import { Geoman, type GmOptionsPartial } from '@geoman-io/maplibre-geoman-free';
const options: GmOptionsPartial = {
settings: {
useControlsUi: true,
controlsPosition: 'top-right',
snapDistance: 20,
throttlingDelay: 50
},
controls: {
draw: {
marker: { uiEnabled: true },
polygon: { uiEnabled: true },
circle: { uiEnabled: false } // Hide circle
},
edit: {
change: { uiEnabled: true },
delete: { uiEnabled: true }
}
}
};
const geoman = new Geoman(map, options);
```
--------------------------------
### Basic Mapbox GL JS Setup with Geoman
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/09-quick-start-guide.md
Initialize a Mapbox GL JS map and the Geoman plugin. Requires a Mapbox access token and sets up a basic map instance.
```typescript
import mapboxgl from "mapbox-gl";
import { Geoman } from "@geoman-io/mapbox-geoman-free";
mapboxgl.accessToken = "YOUR_TOKEN";
const map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/streets-v12",
center: [0, 51],
zoom: 5
});
const geoman = new Geoman(map);
map.on("gm:loaded", async () => {
console.log("Geoman ready!");
});
```
--------------------------------
### TypeScript Type Signature Example
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/README.md
Illustrates the exact TypeScript type signatures provided in the documentation. Full type definitions are available in a separate file.
```typescript
async enableMode(
actionType: ModeType,
modeName: ModeName
): Promise
```
--------------------------------
### Basic MapLibre GL JS Setup with Geoman
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/09-quick-start-guide.md
Initialize a MapLibre GL JS map and the Geoman plugin. Includes necessary CSS imports and enables drawing mode after Geoman is loaded.
```typescript
import ml from "maplibre-gl";
import { Geoman, type GmOptionsPartial } from "@geoman-io/maplibre-geoman-free";
import "maplibre-gl/dist/maplibre-gl.css";
import "@geoman-io/maplibre-geoman-free/dist/maplibre-geoman.css";
// Create map
const map = new ml.Map({
container: "map",
style: {
version: 8,
sources: {
osm: {
type: "raster",
tiles: ["https://tile.openstreetmap.org/{z}/{x}/{y}.png"],
tileSize: 256
}
},
layers: [
{
id: "osm-layer",
type: "raster",
source: "osm",
minzoom: 0,
maxzoom: 19
}
]
},
center: [0, 51],
zoom: 5
});
// Initialize Geoman
const geoman = new Geoman(map);
// Listen for when Geoman is loaded
map.on("gm:loaded", async () => {
console.log("Geoman ready!");
// Enable drawing mode
await geoman.enableDraw("polygon");
});
```
--------------------------------
### get
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/02-features-api.md
Get a specific feature by its ID and source name.
```APIDOC
## get
### Description
Get a specific feature by its ID and source name.
### Method
```typescript
get(sourceName: keyof SourcesStorage, featureId: FeatureId): FeatureData | null
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **sourceName** ('main' | 'temporary' | 'internal') - Required - Source where feature is stored
- **featureId** (FeatureId) - Required - Feature identifier
### Request Example
```typescript
const feature = geoman.features.get('main', 'feature-1');
if (feature) {
console.log(`Found: ${feature.shape}`);
}
```
### Response
#### Success Response (200)
- **FeatureData | null** - The feature data if found, otherwise null
#### Response Example
```json
{
"type": "Feature",
"geometry": { ... },
"properties": { ... }
}
```
```
--------------------------------
### getAll
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/02-features-api.md
Get all features as GeoJSON. This is a shorthand for `exportGeoJson()`.
```APIDOC
## getAll
### Description
Get all features as GeoJSON. This is a shorthand for `exportGeoJson()`.
### Method
```typescript
getAll(): FeatureCollection
```
### Parameters
None
### Request Example
```typescript
const allFeatures = geoman.features.getAll();
```
### Response
#### Success Response (200)
- **FeatureCollection** - GeoJSON FeatureCollection of all features
#### Response Example
```json
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": { ... },
"properties": { ... }
}
]
}
```
```
--------------------------------
### Example CSS for Control Buttons
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/07-gm-control.md
Provides basic styling for individual control buttons and their active state. Use these classes to customize the appearance of the Geoman control UI.
```css
.gm-control-button {
padding: 8px 12px;
background: white;
border: 1px solid #ddd;
border-radius: 4px;
cursor: pointer;
}
.gm-control-button--active {
background: #007bff;
color: white;
}
```
--------------------------------
### Track Feature Selection Changes
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/04-events-system.md
This example shows how to monitor when the selection of features on the map changes. It logs the number of currently selected features.
```typescript
map.on('gm:edit', (event) => {
if (event.action === 'selection_change') {
console.log(`Selected ${event.selection.length} features`);
}
});
```
--------------------------------
### Initialize Geoman Instance (TypeScript)
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/README.md
Instantiate the Geoman class with a map object. This is a basic setup for using Geoman's drawing and editing tools.
```typescript
// TypeScript syntax highlighting
const geoman = new Geoman(map);
```
--------------------------------
### Configure Draw and Edit Controls
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/09-quick-start-guide.md
Optimize performance by disabling features you don't need. This example shows how to selectively enable specific draw shapes and edit operations.
```typescript
controls: {
draw: { /* enable only needed shapes */ },
edit: { /* enable only needed operations */ }
}
```
--------------------------------
### Implement Accessible Control Button
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/07-gm-control.md
Ensure custom control implementations are keyboard-accessible by including ARIA attributes. This example shows a button with appropriate roles and labels for screen readers and keyboard navigation.
```html
Polygon
```
--------------------------------
### Listen for Draw Finish/Cancel Events
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/04-events-system.md
This example shows how to detect when a drawing operation is finished or canceled. It filters the 'gm:draw' event for the 'finish' action.
```typescript
map.on('gm:draw', (event) => {
if (event.action === 'finish') {
console.log(`Finished drawing ${event.mode}`);
}
});
```
--------------------------------
### Create Geoman Instance
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/01-geoman-main-class.md
Factory function to create and initialize a Geoman instance. Use this to start using Geoman with your map. It returns a Promise that resolves with the Geoman instance or rejects if initialization fails.
```typescript
async function createGeomanInstance(
map: AnyMapInstance,
options: PartialDeep
): Promise
```
```typescript
try {
const geoman = await createGeomanInstance(map, {
settings: { useControlsUi: true }
});
console.log("Geoman ready");
} catch (error) {
console.error("Failed to initialize:", error);
}
```
--------------------------------
### Listen to Draw Mode Events
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/08-modes-draw-edit-helper.md
Use `map.on('gm:draw', ...)` to listen for events during drawing operations. This includes starting a mode, progress updates, and feature creation.
```typescript
map.on('gm:draw', (event) => {
if (event.action === 'mode_start') {
console.log(`Started drawing: ${event.mode}`);
}
if (event.action === 'update') {
console.log('Drawing progress:', event.featureData);
}
if (event.action === 'feature_created') {
console.log('Feature created:', event.featureData.getGeoJson());
}
});
```
--------------------------------
### Validate Features Before Creation
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/09-quick-start-guide.md
Listen for the 'gm:feature' event and implement custom validation logic within the 'before_create' action. This example rejects features with an area smaller than 1000 square meters.
```typescript
map.on("gm:feature", (event) => {
if (event.action === "before_create") {
// Validate before creating
for (const geojson of event.geoJsonFeatures) {
// Example: reject very small areas
const area = turf.area(geojson);
if (area < 1000) {
// 1000 square meters minimum
throw new Error("Feature is too small");
}
}
}
});
```
--------------------------------
### Get All Features (Shorthand)
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/02-features-api.md
A shorthand method to get all features as a GeoJSON FeatureCollection, equivalent to calling `exportGeoJson()`.
```typescript
const allFeatures = geoman.features.getAll();
```
--------------------------------
### Run Smoke Tests and Full Test Suite
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/README.md
Execute smoke tests for specific adapters (MapLibre, Mapbox) using a particular project and browser, or run the full test suite for all variants.
```shell
pnpm run test:maplibre --project=chromium --grep="@smoke"
pnpm run test:mapbox --project=chromium --grep="@smoke"
pnpm run test:all
```
--------------------------------
### Initialize Mapbox Map and Geoman
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/packages/mapbox/README.md
Import necessary libraries, configure Mapbox access token, initialize a Mapbox map, and then initialize Geoman with the map instance. Ensure Geoman is loaded before proceeding.
```typescript
import mapboxgl from 'mapbox-gl';
import { Geoman, type GmOptionsPartial } from '@geoman-io/mapbox-geoman-free';
import 'mapbox-gl/dist/mapbox-gl.css';
import '@geoman-io/mapbox-geoman-free/dist/mapbox-geoman.css';
mapboxgl.accessToken = '';
const map = new mapboxgl.Map({
container: 'dev-map',
style: {
version: 8,
glyphs: 'https://fonts.openmaptiles.org/{fontstack}/{range}.pbf',
sources: {
'osm-tiles': {
type: 'raster',
tiles: ['https://tile.openstreetmap.org/{z}/{x}/{y}.png'],
tileSize: 256,
attribution: '© OpenStreetMap contributors',
},
},
layers: [
{
id: 'osm-tiles-layer',
type: 'raster',
source: 'osm-tiles',
minzoom: 0,
maxzoom: 19,
},
],
},
center: [0, 51],
zoom: 5,
});
const geoman = new Geoman(map);
await geoman.waitForGeomanLoaded();
```
--------------------------------
### Get Shape-Specific Property
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/02-features-api.md
Retrieve a shape-specific property, such as fill color or stroke width, from a feature. Optionally, provide input GeoJSON to get properties from a specific representation.
```typescript
const fillColor = feature.getShapeProperty('fillColor');
const strokeWidth = feature.getShapeProperty('strokeWidth');
```
--------------------------------
### Initialize Geoman with Options
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/01-geoman-main-class.md
Instantiate the Geoman class with a map instance and optional configuration settings. Ensure you import the necessary Geoman and map library components.
```typescript
import { Geoman, type GmOptionsPartial } from "@geoman-io/maplibre-geoman-free";
import ml from "maplibre-gl";
const map = new ml.Map({ container: "map", style: {...}, center: [0, 51], zoom: 5 });
const options: GmOptionsPartial = { settings: { snapDistance: 25 } };
const geoman = new Geoman(map, options);
```
--------------------------------
### Configure Modes via Options
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/08-modes-draw-edit-helper.md
Shows how to configure drawing modes, including their active state and UI visibility, during Geoman initialization.
```APIDOC
## Configure Modes via Options
```typescript
const geoman = new Geoman(map, {
controls: {
draw: {
polygon: { active: true, uiEnabled: true },
circle: { active: false, uiEnabled: true } // Hidden but available
}
}
});
```
```
--------------------------------
### Get Active Modes
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/01-geoman-main-class.md
Retrieves lists of currently enabled modes in different categories.
```APIDOC
## getActiveDrawModes
### Description
Gets a list of currently enabled drawing modes.
### Method
`getActiveDrawModes(): Array`
### Response
#### Success Response (200)
- **Array** - An array of strings representing the names of the active draw modes.
```
```APIDOC
## getActiveEditModes
### Description
Gets a list of currently enabled editing modes.
### Method
`getActiveEditModes(): Array`
### Response
#### Success Response (200)
- **Array** - An array of strings representing the names of the active edit modes.
```
```APIDOC
## getActiveHelperModes
### Description
Gets a list of currently enabled helper modes.
### Method
`getActiveHelperModes(): Array`
### Response
#### Success Response (200)
- **Array** - An array of strings representing the names of the active helper modes.
```
--------------------------------
### GmEditModeEvent
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/04-events-system.md
Fired when edit mode is enabled or disabled. It indicates the start or end of an editing mode.
```APIDOC
## GmEditModeEvent
### Description
Fired when edit mode is enabled/disabled.
### Event Name
gm:edit:mode
### Event Payload
```typescript
interface GmEditModeEvent extends GmBaseModeEvent {
name: `gm:edit:mode`;
actionType: 'edit';
mode: EditModeName;
action: 'mode_start' | 'mode_started' | 'mode_end' | 'mode_ended';
}
```
### Example
```typescript
map.on('gm:edit', (event) => {
if (event.action === 'mode_started' && event.mode === 'change') {
console.log('Edit mode activated');
}
});
```
```
--------------------------------
### Get features by screen bounds
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/02-features-api.md
Retrieves all features that fall within the specified screen coordinate boundaries.
```typescript
getFeaturesByScreenBounds(options: {
bounds: [ScreenPoint, ScreenPoint];
sourceNames: Array;
}): Array
```
--------------------------------
### Constructor
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/01-geoman-main-class.md
Initializes the Geoman plugin with a map instance and optional configuration. It sets up core components, registers the map adapter, and waits for the base map to load.
```APIDOC
## Constructor
```typescript
constructor(map: AnyMapInstance, options: PartialDeep = {})
```
### Description
Initializes the Geoman plugin with a map instance and optional configuration. It sets up core components, registers the map adapter, and waits for the base map to load.
### Parameters
#### Path Parameters
- **map** (`AnyMapInstance`) - Required - MapLibre or Mapbox map instance
- **options** (`PartialDeep`) - Optional - Configuration options (partial merge with defaults)
### Request Example
```typescript
import { Geoman, type GmOptionsPartial } from "@geoman-io/maplibre-geoman-free";
import ml from "maplibre-gl";
const map = new ml.Map({ container: "map", style: {...}, center: [0, 51], zoom: 5 });
const options: GmOptionsPartial = { settings: { snapDistance: 25 } };
const geoman = new Geoman(map, options);
```
```
--------------------------------
### Initialize Maplibre-Geoman
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/packages/maplibre/README.md
Import necessary libraries and initialize Maplibre-Geoman with a MapLibre GL JS map instance. Ensure MapLibre GL JS and Geoman CSS are imported.
```typescript
import ml from 'maplibre-gl';
import { Geoman, type GmOptionsPartial } from '@geoman-io/maplibre-geoman-free';
import 'maplibre-gl/dist/maplibre-gl.css';
import '@geoman-io/maplibre-geoman-free/dist/maplibre-geoman.css';
const map = new ml.Map({
container: 'dev-map',
style: {
version: 8,
glyphs: 'https://fonts.openmaptiles.org/{fontstack}/{range}.pbf',
sources: {
'osm-tiles': {
type: 'raster',
tiles: ['https://tile.openstreetmap.org/{z}/{x}/{y}.png'],
tileSize: 256,
attribution: '© OpenStreetMap contributors',
},
},
layers: [
{
id: 'osm-tiles-layer',
type: 'raster',
source: 'osm-tiles',
minzoom: 0,
maxzoom: 19,
},
],
},
center: [0, 51],
zoom: 5,
});
const geoman = new Geoman(map);
map.on('gm:loaded', () => {
console.log('Geoman fully loaded');
});
```
--------------------------------
### Get features by GeoJSON bounds
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/02-features-api.md
Fetches all features that intersect with a provided GeoJSON geometry (Polygon, MultiPolygon, or LineString).
```typescript
getFeaturesByGeoJsonBounds(options: {
geoJson: Feature;
sourceNames: Array;
}): Array
```
--------------------------------
### GmEditMarkerMoveEvent
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/04-events-system.md
Fired when a feature marker (vertex, handle) is dragged. Provides information about the start and end coordinates of the drag.
```APIDOC
## GmEditMarkerMoveEvent
### Description
Fired when a feature marker (vertex, handle) is dragged.
### Event Name
gm:edit:marker_move
### Event Payload
```typescript
interface GmEditMarkerMoveEvent extends GmBaseEvent {
name: `gm:edit:marker_move`;
actionType: 'edit';
mode: EditModeName;
action: 'marker_move';
featureData: FeatureData;
markerData: MarkerData;
lngLatStart: LngLatTuple;
lngLatEnd: LngLatTuple;
linkedFeatures: FeatureData[];
}
```
### Fields
| Field | Type | Description |
|-------|------|-------------|
| `featureData` | FeatureData | Feature being edited |
| `markerData` | MarkerData | Marker being moved |
| `lngLatStart` | [lng, lat] | Starting coordinates |
| `lngLatEnd` | [lng, lat] | Ending coordinates |
| `linkedFeatures` | FeatureData[] | Features moved together (grouped) |
### Example
```typescript
map.on('gm:edit', (event) => {
if (event.action === 'marker_move') {
const distance = haversineDistance(event.lngLatStart, event.lngLatEnd);
console.log(`Moved ${distance}km`);
}
});
```
```
--------------------------------
### Run Project Checks and Builds
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/README.md
Execute various checks and build commands for the project, including validation, linting, type checking, and building all variants.
```shell
pnpm run workspace:validate
pnpm run lint:all
pnpm run typecheck:all
pnpm run build:all
```
--------------------------------
### Get Difference Between Coordinates
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/06-utilities.md
Calculates the difference between two LngLatTuple coordinates. Returns a tuple representing the difference in longitude and latitude.
```typescript
function getLngLatDiff(lngLat1: LngLatTuple, lngLat2: LngLatTuple): LngLatTuple
```
--------------------------------
### Get GeoJSON Representation of a Feature
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/02-features-api.md
Retrieve the GeoJSON representation of a feature. This is useful for exporting feature data or integrating with other GeoJSON-compatible libraries.
```typescript
const feature = geoman.features.get('main', 'feature-1');
const geojson = feature.getGeoJson();
console.log(geojson.geometry.type);
```
--------------------------------
### Basic Geoman Configuration
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/09-quick-start-guide.md
Initialize Geoman with basic settings to enable the control panel, set its position, define snap distance, and control default layer rendering and cursor feedback.
```typescript
const geoman = new Geoman(map, {
settings: {
useControlsUi: true, // Show control panel
controlsPosition: "top-left", // Panel position
snapDistance: 20, // Snap tolerance (pixels)
useDefaultLayers: true, // Render features on map
useCursorHandlers: true // Show cursor feedback
},
controls: {
draw: {
polygon: { uiEnabled: true },
marker: { uiEnabled: true },
circle: { uiEnabled: false } // Hide circle
}
}
});
```
--------------------------------
### Get Geoman Control Options
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/03-gm-options.md
Retrieve the configuration object for a specific drawing or editing control. Returns null if the control is not found.
```typescript
getControlOptions(options: {
modeType: ModeType;
modeName: ModeName;
}): ControlOptions | null
```
--------------------------------
### Get First Coordinate from Geometry
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/06-utilities.md
Extracts the first coordinate from any GeoJSON geometry type. Returns null if the geometry is empty or does not contain coordinates.
```typescript
function getGeoJsonFirstPoint(geometry: Geometry): LngLatTuple | null
```
--------------------------------
### Configure .npmrc for Maplibre Geoman Pro
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/README.md
Add this content to your .npmrc file in the project root to configure access to the pro version registry. Replace `` with your actual license key.
```shell
#.npmrc
@geoman-io:registry=https://npm.geoman.io/
//npm.geoman.io/:_authToken=""
```
--------------------------------
### Get Active Geoman Helper Modes
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/01-geoman-main-class.md
Retrieves an array of currently enabled helper modes. Useful for understanding the active utility modes.
```typescript
getActiveHelperModes(): Array
```
--------------------------------
### createControls
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/07-gm-control.md
Creates the control UI and attaches it to a specified HTML element. This method sets up all available mode buttons, attaches click handlers for mode switching, and manages the collapsed/expanded state and custom styling.
```APIDOC
## createControls
### Description
Create control UI and attach to a custom HTML element.
### Method Signature
```typescript
async createControls(element: HTMLElement): Promise
```
### Parameters
#### Path Parameters
- **element** (HTMLElement) - Required - Container element for controls
### Behavior
- Creates control buttons for all available modes
- Attaches click handlers for mode switching
- Renders collapsed/expanded state based on options
- Applies custom styles from configuration
### Example
```typescript
const controlContainer = document.getElementById('controls');
await geoman.control.createControls(controlContainer);
```
```
--------------------------------
### Get Active Geoman Edit Modes
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/01-geoman-main-class.md
Retrieves an array of currently enabled editing modes. Use this to determine which editing features are active.
```typescript
getActiveEditModes(): Array
```
--------------------------------
### Basic HTML Structure for Map
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/09-quick-start-guide.md
A minimal HTML structure to host the map. Ensure a div with the ID 'map' is present.
```html
Geoman Example
```
--------------------------------
### Get Active Geoman Draw Modes
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/01-geoman-main-class.md
Retrieves an array of currently enabled drawing modes. Useful for checking the state of drawing functionalities.
```typescript
getActiveDrawModes(): Array
```
```typescript
const activeModes = geoman.getActiveDrawModes();
console.log(activeModes); // ['marker', 'polygon']
```
--------------------------------
### GmDrawModeEvent Interface
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/04-events-system.md
Defines the structure for events related to the start and end of drawing modes. Includes properties for the drawing mode name and action.
```typescript
interface GmDrawModeEvent extends GmBaseModeEvent {
name: `gm:draw:mode`;
actionType: 'draw';
mode: DrawModeName;
action: 'mode_start' | 'mode_started' | 'mode_end' | 'mode_ended';
}
```
--------------------------------
### Initialize Geoman Instance
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/README.md
Instantiate the Geoman class with a MapLibre map instance and options. Waits for Geoman to be fully loaded before proceeding.
```typescript
import { Geoman } from '@geoman-io/maplibre-geoman-free';
const geoman = new Geoman(map, options);
await geoman.waitForGeomanLoaded();
```
--------------------------------
### Listening to Events via Map Instance
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/04-events-system.md
Demonstrates how to listen to specific Geoman events directly on the MapLibre map instance.
```APIDOC
## Listening to Events via Map Instance
### Description
Listen to specific Geoman events directly on the MapLibre map instance.
### Example
```typescript
map.on('gm:draw', (event) => {
console.log('Draw event:', event);
});
map.on('gm:edit', (event) => {
console.log('Edit event:', event);
});
map.on('gm:feature', (event) => {
console.log('Feature event:', event);
});
```
```
--------------------------------
### Initialize Geoman with Options
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/03-gm-options.md
Configure Geoman during initialization by passing an options object. This allows setting various parameters like snap distance and control UI visibility.
```typescript
const geoman = new Geoman(map, {
settings: {
snapDistance: 25,
useControlsUi: true
},
controls: {
draw: {
marker: { active: true, uiEnabled: true }
},
edit: {
change: { active: false }
}
},
layerStyles: { /* custom styles */ }
});
```
--------------------------------
### Enable Collapsible Controls
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/07-gm-control.md
Make the Geoman control panel collapsible by setting `controlsCollapsible` to true. `controlsUiEnabledByDefault` determines if controls start in an expanded state.
```typescript
const geoman = new Geoman(map, {
settings: {
controlsCollapsible: true,
controlsUiEnabledByDefault: true // Start expanded
}
});
```
--------------------------------
### Configure Helper Controls
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/03-gm-options.md
Configure utility controls that assist with map interactions, such as snapping, measurements, and zoom functionalities. Each control can be customized with a title.
```typescript
controls: {
helper: {
shape_markers: { title: 'Shape Markers', ... },
pin: { title: 'Pin', ... },
snapping: { title: 'Snapping', ... },
snap_guides: { title: 'Snap Guides', ... },
measurements: { title: 'Measurements', ... },
auto_trace: { title: 'Auto Trace', ... },
geofencing: { title: 'Geofencing', ... },
zoom_to_features: { title: 'Zoom', ... },
click_to_edit: { title: 'Click Edit', ... }
}
}
```
--------------------------------
### Initialize Mapbox Geoman
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/README.md
This snippet demonstrates initializing Mapbox Geoman with a Mapbox GL JS map. It requires a Mapbox access token and CSS imports. The `waitForGeomanLoaded` method is used to ensure Geoman is ready before proceeding.
```typescript
import mapboxgl from "mapbox-gl";
import { Geoman, type GmOptionsPartial } from "@geoman-io/mapbox-geoman-free";
import "mapbox-gl/dist/mapbox-gl.css";
import "@geoman-io/mapbox-geoman-free/dist/mapbox-geoman.css";
mapboxgl.accessToken = import.meta.env.VITE_MAPBOX_TOKEN ?? "";
const mapStyle: mapboxgl.StyleSpecification = {
version: 8,
glyphs: "https://fonts.openmaptiles.org/{fontstack}/{range}.pbf",
sources: {
"osm-tiles": {
type: "raster",
tiles: ["https://tile.openstreetmap.org/{z}/{x}/{y}.png"],
tileSize: 256,
attribution: "© OpenStreetMap contributors",
},
},
layers: [
{
id: "osm-tiles-layer",
type: "raster",
source: "osm-tiles",
minzoom: 0,
maxzoom: 19,
},
],
};
const map = new mapboxgl.Map({
container: "dev-map",
style: mapStyle,
center: [0, 51],
zoom: 5,
});
const gmOptions: GmOptionsPartial = {
// geoman options here
};
const geoman = new Geoman(map, gmOptions);
await geoman.waitForGeomanLoaded();
```
--------------------------------
### Get feature by mouse event
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/02-features-api.md
Retrieves the topmost feature at a given mouse event location, preferring markers over shapes. Returns null if no feature is under the cursor.
```typescript
getFeatureByMouseEvent(options: {
event: BaseMapPointerEvent;
sourceNames: Array;
}): FeatureData | null
```
```typescript
map.on('click', (event) => {
const feature = geoman.features.getFeatureByMouseEvent({
event,
sourceNames: ['main']
});
if (feature) {
console.log(`Clicked on: ${feature.id}`);
}
});
```
--------------------------------
### Get Specific Feature by ID
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/02-features-api.md
Retrieve a specific feature by its ID and source name ('main', 'temporary', or 'internal'). Returns the feature data or null if not found.
```typescript
const feature = geoman.features.get('main', 'feature-1');
if (feature) {
console.log(`Found: ${feature.shape}`);
}
```
--------------------------------
### Drawing Convenience Methods
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/01-geoman-main-class.md
These methods provide shortcuts for enabling, disabling, and toggling drawing modes. They are equivalent to calling `enableMode('draw', shape)`, etc.
```APIDOC
## enableDraw
### Description
Enables a specific drawing mode.
### Method
`async enableDraw(shape: DrawModeName): Promise`
### Parameters
#### Path Parameters
- **shape** (DrawModeName) - Required - The name of the drawing mode to enable (e.g., 'marker', 'polygon').
```
```APIDOC
## disableDraw
### Description
Disables the currently active drawing mode.
### Method
`async disableDraw(): Promise`
```
```APIDOC
## toggleDraw
### Description
Toggles a specific drawing mode on or off.
### Method
`async toggleDraw(shape: DrawModeName): Promise`
### Parameters
#### Path Parameters
- **shape** (DrawModeName) - Required - The name of the drawing mode to toggle (e.g., 'marker', 'polygon').
```
```APIDOC
## drawEnabled
### Description
Checks if a specific drawing mode is currently enabled.
### Method
`drawEnabled(shape: DrawModeName): boolean`
### Parameters
#### Path Parameters
- **shape** (DrawModeName) - Required - The name of the drawing mode to check (e.g., 'marker', 'polygon').
```
--------------------------------
### Configure and Enable Snapping
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/08-modes-draw-edit-helper.md
Configure the snap distance in pixels and enable the snapping helper. The default snap distance is 18 pixels.
```typescript
const geoman = new Geoman(map, {
settings: {
snapDistance: 18 // pixels, default 18
}
});
// Enable snapping
await geoman.enableMode('helper', 'snapping');
```
--------------------------------
### Custom Layer Styles
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/09-quick-start-guide.md
Define custom styles for map features by extending the default layer styles. This example customizes the fill and stroke properties of polygons.
```typescript
import { defaultLayerStyles } from "@geoman-io/maplibre-geoman-free";
const geoman = new Geoman(map, {
layerStyles: {
...defaultLayerStyles,
polygon: {
...defaultLayerStyles.polygon,
fillColor: "#FF0000",
strokeColor: "#000000",
strokeWidth: 2
}
}
});
```
--------------------------------
### forEach / tmpForEach
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/02-features-api.md
Iterate over features with a callback function. `forEach` iterates permanent features, `tmpForEach` iterates temporary features.
```APIDOC
## forEach / tmpForEach
### Description
Iterate over features with a callback function. `forEach` iterates permanent features, `tmpForEach` iterates temporary features.
### Method
```typescript
forEach: (callbackfn: ForEachFeatureDataCallbackFn) => void
tmpForEach: (callbackfn: ForEachFeatureDataCallbackFn) => void
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **callbackfn** (ForEachFeatureDataCallbackFn) - Required - Function to execute for each feature
- **featureData** (FeatureData) - The feature data
- **featureId** (FeatureId) - The feature identifier
- **featureStore** (FeatureStore) - The feature store
### Request Example
```typescript
geoman.features.forEach((featureData, featureId) => {
console.log(`Feature ${featureId}: ${featureData.shape}`);
});
```
### Response
None
#### Response Example
None
```
--------------------------------
### Geoman Classes
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/README.md
The main entry point and core components of the Geoman library are exposed through several classes that manage configuration, events, controls, and features.
```APIDOC
## Classes
- `Geoman` — Main entry point
- `GmOptions` — Configuration management
- `GmEvents` — Event system
- `GmControl` — UI controls
- `Features` — Feature management
- `FeatureData` — Individual feature data
- Base classes for extending (BaseDraw, BaseEdit, BaseHelper, etc.)
```
--------------------------------
### Shape Markers Constants
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/05-types.md
Defines constants for special shape names used in Geoman, including markers for DOM elements, vertices, centers, edges, and snap guides.
```APIDOC
## Shape Markers
```typescript
export const SPECIAL_SHAPE_NAMES: readonly [
'dom_marker',
'vertex_marker',
'center_marker',
'edge_marker',
'snap_guide'
];
export const ALL_SHAPE_NAMES: readonly [
// SHAPE_NAMES + SPECIAL_SHAPE_NAMES
];
```
```
--------------------------------
### Configure Geoman Modes via Options
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/08-modes-draw-edit-helper.md
Initialize Geoman with specific mode configurations. This allows setting modes like 'draw' or 'edit' to active or inactive states, and controlling UI visibility during instantiation.
```typescript
const geoman = new Geoman(map, {
controls: {
draw: {
polygon: { active: true, uiEnabled: true },
circle: { active: false, uiEnabled: true } // Hidden but available
}
}
});
```
--------------------------------
### Import Default Layer Styles
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/03-gm-options.md
Import the default layer styles to use as a base for customization.
```typescript
import { defaultLayerStyles } from '@geoman-io/maplibre-geoman-free';
```
--------------------------------
### Get Active Draw, Edit, and Helper Modes
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/08-modes-draw-edit-helper.md
Retrieve arrays of currently active draw, edit, and helper modes. Useful for understanding the current state of the Geoman instance.
```typescript
const activeDraw = geoman.getActiveDrawModes(); // ['polygon']
const activeEdit = geoman.getActiveEditModes(); // ['change', 'rotate']
const activeHelper = geoman.getActiveHelperModes(); // ['snapping']
```
--------------------------------
### Listen for Draw Mode Start/End Events
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/04-events-system.md
Use this snippet to log when a drawing mode is started or ended. It listens for the 'gm:draw' event and checks the 'action' property for 'mode_started'.
```typescript
map.on('gm:draw', (event) => {
if (event.action === 'mode_started') {
console.log(`Started drawing: ${event.mode}`);
}
});
```
--------------------------------
### Legacy Global Edit Mode Shortcuts
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/08-modes-draw-edit-helper.md
Convenience methods for enabling various global editing modes.
```APIDOC
## Enable Global Drag Mode
```typescript
await geoman.enableGlobalDragMode();
```
## Enable Global Edit Mode
```typescript
await geoman.enableGlobalEditMode();
```
## Enable Global Rotate Mode
```typescript
await geoman.enableGlobalRotateMode();
```
## Enable Global Cut Mode
```typescript
await geoman.enableGlobalCutMode();
```
## Enable Global Removal Mode
```typescript
await geoman.enableGlobalRemovalMode();
```
```
--------------------------------
### GmDrawShapeEventWithData Interface
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/04-events-system.md
This interface defines events that occur during drawing progress, providing feature data. It includes the drawing action (start, update, finish) and associated marker or feature data.
```typescript
interface GmDrawShapeEventWithData extends GmBaseEvent {
name: `gm:draw:shape_with_data`;
actionType: 'draw';
mode: DrawModeName;
action: 'start' | 'update' | 'finish';
markerData: MarkerData | null;
featureData: FeatureData | null;
}
```
--------------------------------
### waitForGeomanLoaded
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/01-geoman-main-class.md
Waits for the Geoman initialization process to complete. It resolves with the Geoman instance if successful, or undefined if the instance was destroyed during initialization.
```APIDOC
## waitForGeomanLoaded
```typescript
async waitForGeomanLoaded(): Promise
```
### Description
Waits for the Geoman initialization process to complete. It resolves with the Geoman instance if successful, or undefined if the instance was destroyed during initialization.
### Returns
`Promise`
### Request Example
```typescript
const gm = await geoman.waitForGeomanLoaded();
if (!gm) {
console.error("Geoman initialization failed");
}
```
```
--------------------------------
### Listening to Events via Global Event Listener
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/04-events-system.md
Shows how to set a global listener to capture all Geoman events.
```APIDOC
## Listening to Events via Global Event Listener
### Description
Set a global listener to capture all Geoman events and handle them type-safely.
### Method
```typescript
geoman.setGlobalEventsListener((event) => {
console.log('All events:', event.name, event.action);
// Type-safe handling
if (event.actionType === 'draw' && event.action === 'feature_created') {
console.log(`Created: ${event.featureData.id}`);
}
});
```
```
--------------------------------
### Global Cut Mode Convenience Methods
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/01-geoman-main-class.md
Methods for enabling, disabling, and toggling the global cut mode.
```APIDOC
## enableGlobalCutMode
### Description
Enables the global cut mode.
### Method
`async enableGlobalCutMode(): Promise`
```
```APIDOC
## disableGlobalCutMode
### Description
Disables the global cut mode.
### Method
`async disableGlobalCutMode(): Promise`
```
```APIDOC
## toggleGlobalCutMode
### Description
Toggles the global cut mode on or off.
### Method
`async toggleGlobalCutMode(): Promise`
```
```APIDOC
## globalCutModeEnabled
### Description
Checks if the global cut mode is currently enabled.
### Method
`globalCutModeEnabled(): boolean`
```
--------------------------------
### Initialize Geoman Correctly
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/09-quick-start-guide.md
Ensure Geoman is fully initialized before calling its methods. Use `waitForGeomanLoaded` to avoid errors.
```typescript
const geoman = new Geoman(map);
await geoman.enableDraw("polygon"); // May fail - not initialized yet
```
```typescript
const geoman = new Geoman(map);
await geoman.waitForGeomanLoaded();
await geoman.enableDraw("polygon");
```
--------------------------------
### Layer Styles Customization
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/03-gm-options.md
Demonstrates how to import default layer styles and customize them for Geoman features.
```APIDOC
## Layer Styles
Custom styling for features on the map. Includes colors, fills, strokes, and marker icons.
**Import defaults:**
```typescript
import { defaultLayerStyles } from '@geoman-io/maplibre-geoman-free';
```
**Customize:**
```typescript
const geoman = new Geoman(map, {
layerStyles: {
...defaultLayerStyles,
marker: { color: '#FF0000' }
}
});
```
```
--------------------------------
### Handle Edit Start and End Operations
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/04-events-system.md
Use these event actions to manage interactions during long-running edit operations. 'feature_edit_start' can be used to disable other map interactions, while 'feature_edit_end' can trigger saving changes.
```typescript
map.on('gm:edit', (event) => {
if (event.action === 'feature_edit_start') {
console.log('Edit started - disable other interactions');
}
if (event.action === 'feature_edit_end') {
console.log('Edit complete - save changes');
}
});
```
--------------------------------
### Global Removal Mode Convenience Methods
Source: https://github.com/geoman-io/maplibre-geoman/blob/master/_autodocs/01-geoman-main-class.md
Methods for enabling, disabling, and toggling the global removal mode.
```APIDOC
## enableGlobalRemovalMode
### Description
Enables the global removal mode.
### Method
`async enableGlobalRemovalMode(): Promise`
```
```APIDOC
## disableGlobalRemovalMode
### Description
Disables the global removal mode.
### Method
`async disableGlobalRemovalMode(): Promise`
```
```APIDOC
## toggleGlobalRemovalMode
### Description
Toggles the global removal mode on or off.
### Method
`async toggleGlobalRemovalMode(): Promise`
```
```APIDOC
## globalRemovalModeEnabled
### Description
Checks if the global removal mode is currently enabled.
### Method
`globalRemovalModeEnabled(): boolean`
```