### Subscribe to TerraDraw Select Event
Source: https://terradraw.water-gis.com/examples/select-event
This example shows how to get the TerraDraw instance and subscribe to its 'select' event. When a feature is selected, its GeoJSON representation is fetched and displayed.
```html
Subscribe select event of TerraDraw
```
--------------------------------
### Initialize Map and Terra Draw with Custom Options
Source: https://terradraw.water-gis.com/examples/drawing-option
Initializes a Maplibre GL map and adds a Terra Draw control with custom drawing modes and options. This example restricts drawing to polygon, select, and delete modes, and further customizes the polygon select mode to disable feature dragging while allowing rotation and scaling.
```html
Customising drawing options
```
--------------------------------
### Configure Undo/Redo Functionality in TerraDraw
Source: https://terradraw.water-gis.com/
Example of configuring the maximum stack size for session and mode-level events, and keyboard shortcuts for undo/redo functionality in TerraDraw.
```javascript
const terraDraw = await getTerraDrawInstance();
terraDraw.setConfiguration({
undo: {
maxStackSize: 50,
},
});
```
--------------------------------
### Customize Drawing Styles with Maplibre GL Terra Draw
Source: https://terradraw.water-gis.com/examples/change-style
This example shows how to change the default drawing styles for points, linestrings, and polygons. It involves configuring the `modeOptions` property of the `MaplibreTerradrawControl` to specify custom colors, widths, and opacities for different drawing elements. Refer to the Terra Draw styling guide for more customization options.
```html
Customising drawing style
```
--------------------------------
### Initialize MaplibreMeasureControl
Source: https://terradraw.water-gis.com/examples/measure-control
This code initializes a MapLibre GL map and adds the MaplibreMeasureControl. Configure the available drawing modes and options like `open` and `computeElevation`.
```html
Measure distance and length of feature
```
--------------------------------
### Configure Undo/Redo with Stack Sizes and Shortcuts
Source: https://terradraw.water-gis.com/examples/custom-undo-redo-config
Configure the maximum stack size for session and mode level events, and define keyboard shortcuts for undo and redo actions. Be aware of potential conflicts with OS-level shortcuts.
```javascript
const drawControl = new MaplibreTerradrawControl.MaplibreTerradrawControl({
modes: ['point', 'linestring', 'polygon', 'select', 'delete', 'undo', 'redo'],
open: true,
/**
* • Configure undo/redo support by passing the `undoRedo` option.
* • Set stack sizes:
- `modeLevel` stack size -> 10 (for in-progress drawing actions)
- `sessionLevel` stack size -> 30 (for committed features)
* • Be mindful of OS/browser-reserved shortcuts:
- Native shortcuts (e.g. ⌘+Z / Ctrl+Z) cannot be overridden reliably in all environments.
- Avoid assigning conflicting combinations that may not trigger consistently.
- If needed, provide alternative shortcuts or allow user customization.
* • Refer to the official TerraDraw guide for details on undo/redo events and configuration:
https://github.com/JamesLMilner/terra-draw/blob/main/guides/6.EVENTS.md#undoredo
*/
undoRedo: {
modeLevel: new terraDraw.TerraDrawModeUndoRedo({ maxStackSize: 40 }),
sessionLevel: new terraDraw.TerraDrawSessionUndoRedo({ maxStackSize: 30 }),
keyboardShortcuts: new terraDraw.TerraDrawUndoRedoKeyboardShortcuts({
undo: [
{
key: 'z',
heldKeys: ['meta', 'control'] // meta = command key in MacOS
}
],
redo: [
{
key: 'z',
heldKeys: ['shift']
}
]
})
}
});
map.addControl(drawControl, 'top-left');
```
--------------------------------
### Initialize Map and Terra Draw Control
Source: https://terradraw.water-gis.com/examples/programmatic-mode-control
Sets up a MapLibre GL map and initializes the Terra Draw control with specified modes. External buttons are then configured to interact with the draw control.
```javascript
const map = new maplibregl.Map({
container: 'map',
style: 'https://demotiles.maplibre.org/style.json',
center: [0, 0],
zoom: 1,
maxPitch: 85
});
// Initialize Terra Draw control with various modes
const drawControl = new MaplibreTerradrawControl.MaplibreTerradrawControl({
modes: [
'render',
'point',
'linestring',
'polygon',
'rectangle',
'circle',
'select',
'delete',
'download'
],
open: true
});
map.addControl(drawControl, 'top-left');
let currentMode = 'render';
const externalButtons = document.querySelectorAll('.mode-button');
// Function to update external button states
function updateExternalButtons(activeMode) {
externalButtons.forEach((button) => {
const buttonMode = button.getAttribute('data-mode');
if (buttonMode === activeMode) {
button.classList.add('active');
} else {
button.classList.remove('active');
}
});
}
// Set initial active state
updateExternalButtons(currentMode);
// Handle external button clicks
externalButtons.forEach((button) => {
button.addEventListener('click', () => {
const mode = button.getAttribute('data-mode');
```
--------------------------------
### Initialize Maplibre GL JS with TerraDraw and Glass Theme
Source: https://terradraw.water-gis.com/examples/glass-theme-control
This HTML and JavaScript code initializes a MapLibre GL JS map, adds the TerraDraw control, and applies the glass theme. It includes necessary script and CSS includes for MapLibre GL JS, TerraDraw, and the custom glass theme.
```html
Custom glass theme control style
```
--------------------------------
### Initialize Map and Terra Draw with Custom Select Styles
Source: https://terradraw.water-gis.com/examples/selected-feature-per-mode-style
Sets up a MapLibre GL map and adds the Terra Draw control. Customizes the 'select' mode to apply different styles to selected polygons, points, and linestrings based on their properties, such as the drawing mode.
```javascript
const map = new maplibregl.Map({
container: 'map',
style: 'https://demotiles.maplibre.org/style.json',
center: [0, 0],
zoom: 1,
maxPitch: 85
});
const drawControl = new MaplibreTerradrawControl.MaplibreTerradrawControl({
modes: [
'point',
'freehand-linestring',
'linestring',
'polygon',
'freehand',
'circle',
'rectangle',
'select',
'delete'
],
open: true,
// style selected features per mode
// see this official guide how to customise style using functions
// https://github.com/JamesLMilner/terra-draw/blob/main/guides/5.STYLING.md#styling-specific-features
modeOptions: {
select: new terraDraw.TerraDrawSelectMode({
styles: {
// Polygons
selectedPolygonColor({ properties }) {
if (properties.mode === 'freehand') return '#ff6b00';
if (properties.mode === 'rectangle') return '#a855f7';
return '#3f97e0';
},
selectedPolygonOutlineColor({ properties }) {
if (properties.mode === 'circle') return '#16a34a';
return '#3f97e0';
},
selectedPolygonFillOpacity: 0.7,
// Points
selectedPointColor: '#f59e0b',
selectedPointOutlineColor: '#000000',
selectedPointOutlineWidth: 2,
selectedPointWidth: 6,
// Linestrings
selectedLineStringColor: ({ properties }) => {
if (properties.mode === 'freehand-linestring') return '#ff51ff';
return '#efff53';
}
})
}
});
map.addControl(drawControl, 'top-left');
```
--------------------------------
### Initialize MapLibre GL and TerraDraw Control
Source: https://terradraw.water-gis.com/examples/add-geojson-customstyle
Sets up a MapLibre GL map and initializes the TerraDraw control with custom modes and styles for polygon, rectangle, and circle drawing. The custom styles define the appearance of these drawing elements.
```javascript
const map = new maplibregl.Map({
container: 'map',
style: 'https://demotiles.maplibre.org/style.json',
center: [0, 0],
zoom: 1,
maxPitch: 85
});
const drawControl = new MaplibreTerradrawControl.MaplibreTerradrawControl({
modes: [
'render',
'angled-rectangle',
'sector',
'polygon',
'rectangle',
'circle',
'select',
'delete-selection'
],
open: true,
// custom terradraw layer style is following.
modeOptions: {
polygon: new terraDraw.TerraDrawPolygonMode({
styles: {
fillColor: '#F5AEAE',
fillOpacity: 0.7,
outlineColor: '#FF0000',
outlineWidth: 2,
closingPointColor: '#FAFAFA',
closingPointWidth: 3,
closingPointOutlineColor: '#FF0000',
closingPointOutlineWidth: 1
}
}),
rectangle: new terraDraw.TerraDrawRectangleMode({
styles: {
fillColor: '#F5AEAE',
fillOpacity: 0.7,
outlineColor: '#FF0000',
outlineWidth: 2
}
}),
circle: new terraDraw.TerraDrawCircleMode({
styles: {
fillColor: '#F5AEAE',
fillOpacity: 0.7,
outlineColor: '#FF0000',
outlineWidth: 2
}
})
}
});
map.addControl(drawControl, 'top-right');
```
--------------------------------
### MapLibre GL JS with TerrainRGB Elevation Query
Source: https://terradraw.water-gis.com/examples/query-elevation-terrainrgb
This HTML and JavaScript code sets up a MapLibre GL map and integrates the MaplibreMeasureControl to query elevation from a TerrainRGB source. Ensure the MapLibre GL JS library and the @watergis/maplibre-gl-terradraw library are included. The `computeElevation` option must be enabled, and a valid `terrainSource` pointing to your DEM tiles must be provided.
```html
Query elevation directly from TerrainRGB
```
--------------------------------
### Use Standard and Measure Control Together
Source: https://terradraw.water-gis.com/
Integrate both the standard MaplibreTerradrawControl and the MaplibreMeasureControl on the same map. This allows users to perform drawing and measurement tasks simultaneously.
```javascript
const map = new maplibregl.Map({
container: "map",
style: "https://demotiles.maplibre.org/style-gl-native/style.json",
center: [-0.078135, 51.511015],
zoom: 12,
});
map.addControl(new MaplibreTerradrawControl(), "top-right");
map.addControl(new MaplibreMeasureControl(), "top-right");
```
--------------------------------
### Maplibre GL JS with Terrain Elevation Query
Source: https://terradraw.water-gis.com/examples/query-elevation-terrain
This HTML and JavaScript code sets up a Maplibre GL JS map, adds a terrain source, and integrates the MaplibreMeasureControl with elevation querying enabled. Ensure the `computeElevation` option is set to `true` for elevation data to be processed.
```html
Query elevation from Maplibre Terrain
```
--------------------------------
### Enable Confirmation Dialog for Deleting Features
Source: https://terradraw.water-gis.com/
Enable a confirmation dialog to appear before deleting features. This prevents accidental deletion and provides a safeguard for user actions.
```javascript
const terraDraw = await getTerraDrawInstance();
terraDraw.setConfiguration({
confirmationDialog: {
delete: true,
},
});
```
--------------------------------
### Programmatic Mode Control with Button Synchronization
Source: https://terradraw.water-gis.com/
Control Terra Draw modes programmatically and synchronize external button states with the plugin's buttons. External actions can activate drawing modes, and the plugin buttons will automatically reflect the current state.
```javascript
const terraDraw = await getTerraDrawInstance();
// Example: Activate 'polygon' mode programmatically
// terraDraw.setMode('polygon');
// The plugin buttons will automatically update to reflect the current mode.
```
--------------------------------
### Configure TerraDraw Control Options
Source: https://terradraw.water-gis.com/
Customize the behavior and appearance of the TerraDraw control, including which drawing modes are enabled and whether the control should be expanded by default.
```javascript
const map = new maplibregl.Map({
container: "map",
style: "https://demotiles.maplibre.org/style-gl-native/style.json",
center: [-0.078135, 51.511015],
zoom: 12,
});
map.addControl(new MaplibreTerradrawControl({
// Example: Remove 'render' mode and keep control expanded
// modes: [
// 'point',
// 'linestring',
// 'polygon',
// // ... other modes except 'render'
// ],
// open: true,
}));
```
--------------------------------
### Programmatically Set TerraDraw Mode
Source: https://terradraw.water-gis.com/examples/programmatic-mode-control
Use this to set the drawing mode programmatically. The `getTerraDrawInstance()` method returns a proxy that automatically syncs plugin button states.
```javascript
const drawInstance = drawControl.getTerraDrawInstance();
if (drawInstance && mode) {
console.log(`Programmatically setting mode to: ${mode}`);
// This will automatically sync the plugin button states
// thanks to the proxy wrapper in getTerraDrawInstance()
drawInstance.setMode(mode);
currentMode = mode;
updateExternalButtons(mode);
}
});
});
```
--------------------------------
### Integrate Standard and Measure Controls
Source: https://terradraw.water-gis.com/examples/use-both-control
Add both MaplibreTerradrawControl and MaplibreMeasureControl to a MapLibre GL JS map. Listen for mode changes on each control to prevent conflicts by resetting the other control's active mode when a new mode is selected.
```html
Using both standard and measure control
```
--------------------------------
### Add Default GeoJSON Features to TerraDraw
Source: https://terradraw.water-gis.com/
Demonstrates how to add GeoJSON features to a TerraDraw instance using the addFeatures() function. Retrieve the TerraDraw instance via getTerraDrawInstance().
```javascript
const terraDraw = await getTerraDrawInstance();
const geojson = {
type: "FeatureCollection",
features: [
{
type: "Feature",
properties: {
"tr-draw-id": "feature-1",
},
geometry: {
type: "Point",
coordinates: [-0.078135, 51.511015],
},
},
],
};
terraDraw.addFeatures(geojson);
```