### Installation and Setup Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Instructions on how to install the Mapbox GL Draw plugin via npm and set it up with Mapbox GL JS, including basic map and draw control initialization. ```APIDOC ## Installation and Setup Install via npm and import both the JavaScript and the required CSS. ```js // Install // npm install @mapbox/mapbox-gl-draw // Module usage import mapboxgl from 'mapbox-gl'; import MapboxDraw from '@mapbox/mapbox-gl-draw'; import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css'; mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN'; const map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v12', center: [-74.5, 40], zoom: 9 }); const draw = new MapboxDraw({ displayControlsDefault: true, // show all toolbar buttons controls: { combine_features: false } // override individual controls }); map.addControl(draw, 'top-left'); // All draw API calls must happen after the map has loaded map.on('load', () => { console.log('Draw ready. Current mode:', draw.getMode()); // => 'simple_select' }); ``` ``` -------------------------------- ### Clone repository and start development server Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/README.md Clone the Mapbox GL Draw repository, install dependencies, build source files, and start the development server. Open the debug page in your browser. ```bash git clone git@github.com:mapbox/mapbox-gl-draw.git npm ci npm start & open "http://localhost:9967/debug/?access_token=" ``` -------------------------------- ### Install and Setup Mapbox GL Draw Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Install the library via npm and import the JavaScript and CSS. Configure Mapbox GL JS and add the Mapbox Draw control to the map. Ensure API calls are made after the map has loaded. ```javascript // Install // npm install @mapbox/mapbox-gl-draw // Module usage import mapboxgl from 'mapbox-gl'; import MapboxDraw from '@mapbox/mapbox-gl-draw'; import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css'; mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN'; const map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v12', center: [-74.5, 40], zoom: 9 }); const draw = new MapboxDraw({ displayControlsDefault: true, // show all toolbar buttons controls: { combine_features: false } // override individual controls }); map.addControl(draw, 'top-left'); // All draw API calls must happen after the map has loaded map.on('load', () => { console.log('Draw ready. Current mode:', draw.getMode()); // => 'simple_select' }); ``` -------------------------------- ### Start Benchmark Server Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/bench/README.md Run this command in your terminal to start the benchmark server. Replace {YOUR MAPBOX ACCESS TOKEN} with your actual token. ```bash MAPBOX_ACCESS_TOKEN={YOUR MAPBOX ACCESS TOKEN} npm run start-bench ``` -------------------------------- ### Install Mapbox GL Draw with npm Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/README.md Use npm to install the library. Ensure you also include the library's CSS. ```bash npm install @mapbox/mapbox-gl-draw ``` -------------------------------- ### Publish to CDN Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/README.md Prepare for publishing by installing dependencies and running the prepublish script. Then, copy the distribution files to the S3 bucket for the CDN. ```bash # make sure you are authenticated for AWS git checkout v{x.y.z} npm ci npm run prepublish aws s3 cp --recursive --acl public-read dist s3://mapbox-gl-js/plugins/mapbox-gl-draw/v{x.y.z} ``` -------------------------------- ### MODE.onTouchStart Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/MODES.md Triggered when a touch event is started. It receives the current state and the event object. ```APIDOC ## MODE.onTouchStart ### Description Triggered when a touch event is started. ### Parameters - `state` {Object} - a mutible state object created by onSetup - `e` {Object} - the captured event that is triggering this life cycle event ``` -------------------------------- ### Install TypeScript types for Mapbox GL Draw Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/README.md Install the DefinitelyTyped package for TypeScript support. ```bash npm install @types/mapbox__mapbox-gl-draw ``` -------------------------------- ### Get All Features with draw.getAll() Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Use `getAll()` to retrieve a GeoJSON FeatureCollection of all features currently managed by Draw. This is useful for saving the current state or logging all features. The example shows how to log the type, count, and coordinates of features, and how to serialize the collection for sending to a server. ```javascript map.on('load', () => { draw.add({ type: 'Point', coordinates: [0, 0] }); draw.add({ type: 'Point', coordinates: [1, 1] }); draw.add({ type: 'Point', coordinates: [2, 2] }); const all = draw.getAll(); console.log(all.type); // => 'FeatureCollection' console.log(all.features.length); // => 3 console.log(all.features[0].geometry.coordinates); // => [0, 0] // Serialize to send to a server fetch('/api/save-map', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(all) }); }); ``` -------------------------------- ### Initialize Mapbox GL Draw Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md Basic setup for integrating Mapbox GL Draw into a Mapbox GL JS map. Ensure the map is loaded before interacting with Draw. ```javascript var map = new Map(mapOptions); var draw = new MapboxDraw(drawOptions); map.addControl(draw); ``` -------------------------------- ### Implement a Custom Draw Mode Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Extend Mapbox GL Draw with custom interaction behaviors by implementing the mode interface and registering it via the `modes` option. This example shows a mode for dropping multiple points. ```javascript // LotsOfPointsMode: click to drop points, Esc to exit const LotsOfPointsMode = {}; LotsOfPointsMode.onSetup = function(opts) { // Called when entering this mode; return the initial state object return { count: opts.count || 0 }; }; LotsOfPointsMode.onClick = function(state, e) { // Create and add a point feature on every click const point = this.newFeature({ type: 'Feature', properties: { index: state.count }, geometry: { type: 'Point', coordinates: [e.lngLat.lng, e.lngLat.lat] } }); this.addFeature(point); state.count += 1; }; LotsOfPointsMode.onKeyUp = function(state, e) { // Esc key exits back to simple_select if (e.keyCode === 27) this.changeMode('simple_select'); }; LotsOfPointsMode.onStop = function(state) { // Cleanup on mode exit — remove any incomplete/invalid features if needed console.log(`Placed ${state.count} points total`); }; // toDisplayFeatures is required — decides which features get rendered LotsOfPointsMode.toDisplayFeatures = function(state, geojson, display) { display(geojson); }; // Register the custom mode alongside built-in modes const draw = new MapboxDraw({ defaultMode: 'lots_of_points', modes: Object.assign({ lots_of_points: LotsOfPointsMode }, MapboxDraw.modes) }); map.addControl(draw); // Programmatically activate with options map.on('load', () => { draw.changeMode('lots_of_points', { count: 10 }); }); ``` -------------------------------- ### Get Selection State with draw.getSelected() and draw.getSelectedIds() Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Use `getSelected()` to get a FeatureCollection of currently selected features, and `getSelectedIds()` to get an array of their IDs. These are useful for reacting to selection changes, as shown in the `draw.selectionchange` event handler. ```javascript map.on('draw.selectionchange', (e) => { const selected = draw.getSelected(); console.log('Selected features:', selected.features.length); const selectedIds = draw.getSelectedIds(); console.log('Selected ids:', selectedIds); // => ['id-abc', 'id-def'] // Inspect the selected geometries selected.features.forEach(f => { console.log(f.geometry.type, f.properties); }); }); ``` -------------------------------- ### Style Lines and Polygons During Drawing with Mapbox GL Draw Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/EXAMPLES.md Define styles for lines and polygons while they are being drawn, including dashed outlines, transparent fills, and distinct vertex styling. This example also styles point vertices with halos. ```javascript var draw = new MapboxDraw({ // other draw options here // ... styles: [ // ACTIVE (being drawn) // line stroke { "id": "gl-draw-line", "type": "line", "filter": ["all", ["==", "$type", "LineString"]], "layout": { "line-cap": "round", "line-join": "round" }, "paint": { "line-color": "#D20C0C", "line-dasharray": [0.2, 2], "line-width": 2 } }, // polygon fill { "id": "gl-draw-polygon-fill", "type": "fill", "filter": ["all", ["==", "$type", "Polygon"]], "paint": { "fill-color": "#D20C0C", "fill-outline-color": "#D20C0C", "fill-opacity": 0.1 } }, // polygon mid points { 'id': 'gl-draw-polygon-midpoint', 'type': 'circle', 'filter': ['all', ['==', '$type', 'Point'], ['==', 'meta', 'midpoint']], 'paint': { 'circle-radius': 3, 'circle-color': '#fbb03b' } }, // polygon outline stroke // This doesn't style the first edge of the polygon, which uses the line stroke styling instead { "id": "gl-draw-polygon-stroke-active", "type": "line", "filter": ["all", ["==", "$type", "Polygon"]], "layout": { "line-cap": "round", "line-join": "round" }, "paint": { "line-color": "#D20C0C", "line-dasharray": [0.2, 2], "line-width": 2 } }, // vertex point halos { "id": "gl-draw-polygon-and-line-vertex-halo-active", "type": "circle", "filter": ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], "paint": { "circle-radius": 5, "circle-color": "#FFF" } }, // vertex points { "id": "gl-draw-polygon-and-line-vertex-active", "type": "circle", "filter": ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], "paint": { "circle-radius": 3, "circle-color": "#D20C0C", } } ] }); ``` -------------------------------- ### Get Selected Features as FeatureCollection Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md Returns a FeatureCollection object containing all currently selected features. ```javascript getSelected(): FeatureCollection ``` -------------------------------- ### this.getSelected Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/MODES.md Gets all selected features as an array of DrawFeature objects. ```APIDOC ## this.getSelected ### Description Get all selected features as a [DrawFeature](https://github.com/mapbox/mapbox-gl-draw/blob/main/src/feature_types/feature.js). ### Returns **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<DrawFeature>** ``` -------------------------------- ### Delete All Features with draw.deleteAll() Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Use `deleteAll()` to remove all features currently in Draw. This method is chainable and returns the draw instance. The example shows how to verify that all features have been removed. ```javascript map.on('load', () => { draw.add({ type: 'Point', coordinates: [0, 0] }); draw.add({ type: 'Point', coordinates: [1, 1] }); draw.deleteAll(); console.log(draw.getAll().features.length); // => 0 // Chainable draw.deleteAll().getAll(); // => { type: 'FeatureCollection', features: [] } }); ``` -------------------------------- ### Change Interaction Mode with draw.changeMode() Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Programmatically transition Mapbox GL Draw into different interaction modes. Use `Draw.modes` enum for mode name constants. Options can pre-select features or specify starting points for drawing. ```javascript map.on('load', () => { // Start drawing a polygon draw.changeMode('draw_polygon'); // Start drawing a point draw.changeMode(MapboxDraw.modes.DRAW_POINT); // Enter simple_select with pre-selected features const [id] = draw.add({ type: 'Point', coordinates: [-74.5, 40] }); draw.changeMode('simple_select', { featureIds: [id] }); // Enter direct_select on a specific feature draw.changeMode('direct_select', { featureId: id }); // Continue drawing an existing LineString from a specific vertex const [lineId] = draw.add({ type: 'Feature', properties: {}, geometry: { type: 'LineString', coordinates: [[-74.5, 40], [-74.0, 40.5]] } }); draw.changeMode('draw_line_string', { featureId: lineId, from: { type: 'Point', coordinates: [-74.0, 40.5] } }); console.log(draw.getMode()); // => 'draw_line_string' }); ``` -------------------------------- ### Get Selected Points as FeatureCollection Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md Returns a FeatureCollection of Point features representing the vertices of currently selected features. ```javascript getSelectedPoints(): FeatureCollection ``` -------------------------------- ### Get All Features as FeatureCollection Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md Retrieves all features currently managed by Draw as a GeoJSON FeatureCollection. ```javascript draw.add({ type: 'Point', coordinates: [0, 0] }); draw.add({ type: 'Point', coordinates: [1, 1] }); draw.add({ type: 'Point', coordinates: [2, 2] }); console.log(draw.getAll()); // { // type: 'FeatureCollection', // features: [ // { // id: 'random-0' // type: 'Feature', // geometry: { // type: 'Point', // coordinates: [0, 0] // } // }, // { // id: 'random-1' // type: 'Feature', // geometry: { // type: 'Point', // coordinates: [1, 1] // } // }, // { // id: 'random-2' // type: 'Feature', // geometry: { // type: 'Point', // coordinates: [2, 2] // } // } // ] // } ``` -------------------------------- ### Get Selected Feature IDs Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md Returns an array of feature IDs for all currently selected features. ```javascript getSelectedIds(): Array ``` -------------------------------- ### draw.modechange Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md Fired when the drawing mode changes. This event occurs just after the current mode stops and just before the next mode starts. ```APIDOC ## draw.modechange ### Description Fired when the mode is changed. The following interactions will trigger this event: - Click the point, line, or polygon buttons to begin drawing (enter a `draw_*` mode). - Finish drawing a feature (enter `simple_select` mode). - While in `simple_select` mode, click on an already selected feature (enter `direct_select` mode). - While in `direct_select` mode, click outside all features (enter `simple_select` mode). This event is fired just after the current mode stops and just before the next mode starts. A render will not happen until after all event handlers have been triggered, so you can force a mode redirect by calling `draw.changeMode()` inside a `draw.modechange` handler. The event data is an object with the following shape: ```js { mode: string // The next mode, i.e. the mode that Draw is changing to } ``` `simple_select` and `direct_select` modes can be initiated with options specific to that mode (see above). ``` -------------------------------- ### Replace All Features with draw.set() Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Use `set(featureCollection)` to replace all existing features with a new set. This method is more efficient than deleting and re-adding features individually as it performs a diff. The example demonstrates loading saved state from an API and also directly setting a FeatureCollection. ```javascript map.on('load', () => { // Load saved state from an API fetch('/api/load-map') .then(res => res.json()) .then(savedCollection => { const ids = draw.set(savedCollection); console.log('Loaded feature ids:', ids); // => ['feature-1', 'feature-2', 'feature-3'] }); // Or replace directly const ids = draw.set({ type: 'FeatureCollection', features: [{ type: 'Feature', id: 'zone-1', properties: { zone: 'A' }, geometry: { type: 'Polygon', coordinates: [[[-74.6, 39.9], [-74.4, 39.9], [-74.4, 40.1], [-74.6, 40.1], [-74.6, 39.9]]] } }] }); console.log(ids); // => ['zone-1'] }); ``` -------------------------------- ### Publish to GitHub and NPM Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/README.md Increment the version, push tags and main branch to GitHub, then publish to NPM. ```bash npm version (major|minor|patch) git push --tags git push npm publish ``` -------------------------------- ### Run tests Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/README.md Execute the test suite for Mapbox GL Draw. ```bash npm run test ``` -------------------------------- ### this.getSelectedIds Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/MODES.md Gets the IDs of all currently selected features. ```APIDOC ## this.getSelectedIds ### Description Get the ids of all currently selected features. ### Returns **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)>** ``` -------------------------------- ### Initialization and Basic Usage Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md Demonstrates how to initialize Mapbox GL Draw and add it to a Mapbox GL JS map. It also shows how to interact with Draw after the map has loaded. ```APIDOC ## Initialization and Basic Usage ### Description This section shows how to create a Mapbox GL JS map, initialize a MapboxDraw control, and add it to the map. It's crucial to interact with Draw only after the map's `load` event has fired. ### Code Example ```js // Create a Mapbox GL JS map var map = new Map(mapOptions); // Create a Draw control var draw = new MapboxDraw(drawOptions); // Add the Draw control to your map map.addControl(draw); // Interact with Draw after the map has loaded map.on('load', function() { draw.add({ ... }); }); ``` ``` -------------------------------- ### Constructor Options Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Details on the configuration options available when instantiating the `MapboxDraw` control, allowing customization of behavior, controls, and modes. ```APIDOC ## Constructor Options `new MapboxDraw(options)` — instantiate the draw control with configuration options. All options are optional. The constructor accepts an object controlling keyboard/touch behavior, toolbar visibility, interaction buffers, the default mode, custom styles, custom modes, and whether API calls emit events. ```js const draw = new MapboxDraw({ keybindings: true, // enable keyboard shortcuts (default: true) touchEnabled: true, // enable touch interactions (default: true) boxSelect: true, // shift+click+drag box-select (default: true) clickBuffer: 2, // px around feature that responds to click (default: 2) touchBuffer: 25, // px around feature that responds to touch (default: 25) displayControlsDefault: false, // hide all controls by default controls: { point: true, // show only point and polygon buttons polygon: true, trash: true }, defaultMode: 'draw_polygon', // start directly in polygon-draw mode userProperties: true, // expose feature props for styling via user_* prefix suppressAPIEvents: false, // emit events even from programmatic API calls }); map.addControl(draw, 'top-right'); ``` ``` -------------------------------- ### Initialize Mapbox GL Draw and Controls Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/debug/index.html Sets up a Mapbox map, adds a Geocoder and NavigationControl, and initializes Mapbox Draw with custom modes. This is the boilerplate for integrating Mapbox GL Draw. ```javascript import mapboxgl from 'mapbox-gl'; import 'mapbox-gl/dist/mapbox-gl.css'; import MapboxGeocoder from '@mapbox/mapbox-gl-geocoder'; import '@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css'; import MapboxDraw from '../index.js'; import '../dist/mapbox-gl-draw.css'; import {getAccessToken} from './access_token_generated.js'; mapboxgl.accessToken = getAccessToken(); const map = new mapboxgl.Map({ container: 'map', zoom: 1, center: [0, 0], }); map.addControl(new MapboxGeocoder({ accessToken: mapboxgl.accessToken, mapboxgl })); map.addControl(new mapboxgl.NavigationControl(), 'top-left'); const modes = MapboxDraw.modes; const Draw = window.Draw = new MapboxDraw({ modes }); let drawIsActive = true; map.addControl(Draw, 'bottom-right'); ``` -------------------------------- ### Mapbox GL Draw Constructor Options Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Instantiate Mapbox GL Draw with various configuration options to control keyboard/touch behavior, toolbar visibility, interaction buffers, default mode, and more. Some options can override individual controls. ```javascript const draw = new MapboxDraw({ keybindings: true, // enable keyboard shortcuts (default: true) touchEnabled: true, // enable touch interactions (default: true) boxSelect: true, // shift+click+drag box-select (default: true) clickBuffer: 2, // px around feature that responds to click (default: 2) touchBuffer: 25, // px around feature that responds to touch (default: 25) displayControlsDefault: false, // hide all controls by default controls: { point: true, // show only point and polygon buttons polygon: true, trash: true }, defaultMode: 'draw_polygon', // start directly in polygon-draw mode userProperties: true, // expose feature props for styling via user_* prefix suppressAPIEvents: false, // emit events even from programmatic API calls }); map.addControl(draw, 'top-right'); ``` -------------------------------- ### MODE.onSetup Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/MODES.md Triggered when a mode is being transitioned into. It receives options and returns a state object. ```APIDOC ## MODE.onSetup ### Description Triggered while a mode is being transitioned into. ### Parameters - `opts` {Object} - this is the object passed via `draw.changeMode('mode', opts)` ### Returns **[Object]** - this object will be passed to all other life cycle functions ``` -------------------------------- ### Import Mapbox GL Draw CSS with modules Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/README.md Import the Mapbox GL Draw CSS file when using a module bundler. ```javascript import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css' ``` -------------------------------- ### Import Mapbox GL Draw with modules Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/README.md Import Mapbox GL JS and Mapbox Draw when using a module bundler. ```javascript import mapboxgl from 'mapbox-gl'; import MapboxDraw from "@mapbox/mapbox-gl-draw"; ``` -------------------------------- ### Get GeoJSON Feature by ID Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md Retrieves a GeoJSON feature from Draw using its unique ID. Returns undefined if no feature matches the ID. ```javascript var featureIds = draw.add({ type: 'Point', coordinates: [0, 0] }); var pointId = featureIds[0]; console.log(draw.get(pointId)); //=> { type: 'Feature', geometry: { type: 'Point', coordinates: [0, 0] } } ``` -------------------------------- ### Configure simple_select mode options Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md When changing to 'simple_select' mode, you can provide an options object to pre-select features by their IDs. ```javascript { // Array of ids of features that will be initially selected featureIds: Array } ``` -------------------------------- ### Get Selected Vertices with draw.getSelectedPoints() Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt In `direct_select` mode, `getSelectedPoints()` returns a FeatureCollection of Points representing the selected vertices. This is useful for inspecting or manipulating individual vertices of a feature. ```javascript map.on('draw.selectionchange', () => { const vertices = draw.getSelectedPoints(); console.log('Selected vertices:', vertices.features.length); vertices.features.forEach(v => { console.log('Vertex at:', v.geometry.coordinates); }); }); ``` -------------------------------- ### Change Drawing Mode to Polygon Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/debug/index.html Activates the 'draw_polygon' mode in Mapbox Draw when a specific UI element is clicked. This allows users to start drawing polygons on the map. ```javascript const startPolygon = document.getElementById('start-polygon'); startPolygon.onclick = function () { Draw.changeMode('draw_polygon'); }; ``` -------------------------------- ### Change Drawing Mode to Line Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/debug/index.html Activates the 'draw_line_string' mode in Mapbox Draw when a specific UI element is clicked. This allows users to start drawing lines on the map. ```javascript const startLine = document.getElementById('start-line'); startLine.onclick = function () { Draw.changeMode('draw_line_string'); }; ``` -------------------------------- ### Define a Custom Mapbox Draw Mode Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/MODES.md Implement lifecycle functions like `onSetup`, `onClick`, `onKeyUp`, and `toDisplayFeatures` to define custom behavior. The `onSetup` function initializes the mode's state, `onClick` handles map clicks, `onKeyUp` manages keyboard events, and `toDisplayFeatures` determines which features are rendered. ```javascript var LotsOfPointsMode = {}; // When the mode starts this function will be called. // The `opts` argument comes from `draw.changeMode('lotsofpoints', {count:7})`. // The value returned should be an object and will be passed to all other lifecycle functions LotsOfPointsMode.onSetup = function(opts) { var state = {}; state.count = opts.count || 0; return state; }; // Whenever a user clicks on the map, Draw will call `onClick` LotsOfPointsMode.onClick = function(state, e) { // `this.newFeature` takes geojson and makes a DrawFeature var point = this.newFeature({ type: 'Feature', properties: { count: state.count }, geometry: { type: 'Point', coordinates: [e.lngLat.lng, e.lngLat.lat] } }); this.addFeature(point); // puts the point on the map }; // Whenever a user clicks on a key while focused on the map, it will be sent here LotsOfPointsMode.onKeyUp = function(state, e) { if (e.keyCode === 27) return this.changeMode('simple_select'); }; // This is the only required function for a mode. // It decides which features currently in Draw's data store will be rendered on the map. // All features passed to `display` will be rendered, so you can pass multiple display features per internal feature. // See `styling-draw` in `API.md` for advice on making display features LotsOfPointsMode.toDisplayFeatures = function(state, geojson, display) { display(geojson); }; ``` -------------------------------- ### Log Benchmark Progress Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/bench/README.md Emit 'log' events to report benchmark progress. These events have a message and an optional color. ```javascript benchmark.fire('log', { message: 'Finished sample ' + i + ' in ' + formatNumber(time) + ' ms' }); ``` -------------------------------- ### Change Drawing Mode to Point Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/debug/index.html Activates the 'draw_point' mode in Mapbox Draw when a specific UI element is clicked. This allows users to start drawing points on the map. ```javascript const startPoint = document.getElementById('start-point'); startPoint.onclick = function () { Draw.changeMode('draw_point'); }; ``` -------------------------------- ### Draw Options Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md Details the various optional configuration settings available when initializing MapboxDraw. ```APIDOC ## Options All of the following options are optional. - `keybindings`: boolean (default `true`) - Whether or not to enable keyboard interactions for drawing. - `touchEnabled`: boolean (default `true`) - Whether or not to enable touch interactions for drawing. - `boxSelect`: boolean (default `true`) - Whether or not to enable box selection of features with `shift`+`click`+drag. If `false`, `shift`+`click`+drag zooms into an area. - `clickBuffer`: number (default: `2`) - Number of pixels around any feature or vertex (in every direction) that will respond to a click. - `touchBuffer`: number (default: `25`) - Number of pixels around any feature of vertex (in every direction) that will respond to a touch. - `controls`: Object - Hide or show individual controls. Each property's name is a control, and value is a boolean indicating whether the control is on or off. Available control names are `point`, `line_string`, `polygon`, `trash`, `combine_features` and `uncombine_features`. By default, all controls are on. To change that default, use `displayControlsDefault`. - `displayControlsDefault`: boolean (default: `true`) - The default value for `controls`. For example, if you would like all controls to be *off* by default, and specify an allowed list with `controls`, use `displayControlsDefault: false`. - `styles`: Array - An array of map style objects. By default, Draw provides a map style for you. To learn about overriding styles, see the [Styling Draw](#styling-draw) section below. - `modes`: Object - Override the default modes with your own. `MapboxDraw.modes` can be used to see the default values. More information on custom modes [can be found here](https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/MODES.md). - `defaultMode`: String (default: `'simple_select'`) - The mode (from `modes`) that user will first land in. - `userProperties`: boolean (default: `false`) - Properties of a feature will also be available for styling and prefixed with `user_`, e.g., `['==', 'user_custom_label', 'Example']`. - `suppressAPIEvents`: boolean (default: `true`) - Whether or not to emit events when calling Draw API methods. If `false`, events will be emitted. ``` -------------------------------- ### Benchmark Event Structure Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/bench/README.md Benchmarks are implemented as functions returning an Evented instance. Use 'log' for progress, 'end' for results, and 'error' for failures. ```javascript createBenchmark(options: { accessToken: string; createMap: (options: { width: number; height: number; ... // supports all options for the Map constructor }):Map }): Evented ``` -------------------------------- ### Get Feature IDs at Pixel Coordinates Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md Returns an array of feature IDs rendered at the specified pixel coordinates (x, y). Useful for interacting with features via mouse events. ```javascript var featureIds = Draw.getFeatureIdsAt({x: 20, y: 20}); console.log(featureIds) //=> ['top-feature-at-20-20', 'another-feature-at-20-20'] ``` -------------------------------- ### Basic Mapbox GL Draw Initialization Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/README.md Initialize Mapbox GL JS, set your access token, and add the Mapbox Draw control to the map. The control defaults to the top-right position if not specified. ```javascript mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN'; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v12', center: [40, -74.50], zoom: 9 }); var Draw = new MapboxDraw(); // Map#addControl takes an optional second argument to set the position of the control. // If no position is specified the control defaults to `top-right`. See the docs // for more details: https://docs.mapbox.com/mapbox-gl-js/api/#map#addcontrol map.addControl(Draw, 'top-left'); map.on('load', function() { // ALL YOUR APPLICATION CODE }); ``` -------------------------------- ### this.setActionableState Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/MODES.md Indicates which actions are currently possible within the mode. Undefined actions default to false. ```APIDOC ## this.setActionableState ### Description Indicate if the different actions are currently possible with your mode See [draw.actionalbe](https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md#draw##actionalbe) for a list of possible actions. All undefined actions are set to **false** by default ### Parameters #### Path Parameters - **actions** (Object) - Optional, defaults to `{}` ``` -------------------------------- ### Get Current Mode with draw.getMode() Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Retrieve the name of the currently active interaction mode in Mapbox GL Draw. This is useful for conditional logic or UI updates based on the drawing state. ```javascript map.on('load', () => { console.log(draw.getMode()); // => 'simple_select' draw.changeMode('draw_polygon'); console.log(draw.getMode()); // => 'draw_polygon' }); map.on('draw.modechange', (e) => { console.log('Mode changed to:', e.mode); // => 'simple_select', 'direct_select', 'draw_polygon', etc. }); ``` -------------------------------- ### Configure direct_select mode options Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md When changing to 'direct_select' mode, you must provide an options object specifying the ID of the feature to be directly selected. ```javascript { // The id of the feature that will be directly selected (required) featureId: string } ``` -------------------------------- ### Get a Feature with draw.get() Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Retrieve a GeoJSON Feature by its ID using the `draw.get(featureId)` method. Returns the Feature object if found, otherwise returns `undefined`. This is useful for inspecting or manipulating existing features. ```javascript map.on('load', () => { const [id] = draw.add({ type: 'Feature', properties: { label: 'HQ' }, geometry: { type: 'Point', coordinates: [-74.5, 40] } }); const feature = draw.get(id); console.log(feature); // { // id: 'abc123', // type: 'Feature', // properties: { label: 'HQ' }, // geometry: { type: 'Point', coordinates: [-74.5, 40] } // } console.log(draw.get('nonexistent')); // => undefined }); ``` -------------------------------- ### API Methods Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md Lists the available programmatic methods on a MapboxDraw instance. ```APIDOC ## API Methods `new MapboxDraw()` returns an instance of Draw with the following API: ``` -------------------------------- ### MODE.onKeyUp Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/MODES.md Triggered when a key up event is detected. It receives the current state and the event object. ```APIDOC ## MODE.onKeyUp ### Description Triggered when a key up event is detected. ### Parameters - `state` {Object} - a mutible state object created by onSetup - `e` {Object} - the captured event that is triggering this life cycle event ``` -------------------------------- ### this.changeMode Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/MODES.md Triggers a mode transition to a new mode with optional options and event configurations. ```APIDOC ## this.changeMode ### Description Trigger a mode change ### Parameters #### Path Parameters - **mode** (String) - the mode to transition into - **opts** (Object) - the options object to pass to the new mode (optional, default `{}`) - **eventOpts** (Object) - used to control what kind of events are emitted. (optional, default `{}`) ``` -------------------------------- ### Handle Mapbox GL Draw Events Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Listen for events like draw.create, draw.update, draw.delete, and draw.modechange to react to user interactions. These events provide feature data and mode information. ```javascript map.on('draw.create', (e) => { console.log('Created:', e.features); // e.features => Array of GeoJSON Feature objects saveToServer(e.features); }); // draw.update — fired when feature(s) are moved or vertices changed map.on('draw.update', (e) => { console.log('Action:', e.action); // 'move' or 'change_coordinates' console.log('Updated:', e.features); }); // draw.delete — fired when feature(s) are deleted by the user map.on('draw.delete', (e) => { console.log('Deleted feature ids:', e.features.map(f => f.id)); }); // draw.selectionchange — fired when selection changes map.on('draw.selectionchange', (e) => { console.log('Now selected:', e.features.length, 'feature(s)'); }); // draw.modechange — fired just before entering the new mode map.on('draw.modechange', (e) => { console.log('Entering mode:', e.mode); // Redirect: force back to simple_select if needed if (e.mode === 'draw_polygon') draw.changeMode('simple_select'); }); // draw.combine / draw.uncombine map.on('draw.combine', (e) => { console.log('Deleted:', e.deletedFeatures.length, '=> Created:', e.createdFeatures.length); }); map.on('draw.uncombine', (e) => { console.log('Split into:', e.createdFeatures.length, 'features'); }); // draw.actionable — tracks which toolbar actions are currently valid map.on('draw.actionable', (e) => { console.log(e.actions); // => { trash: true, combineFeatures: false, uncombineFeatures: false } }); // draw.render — fired whenever Draw calls setData() on the map map.on('draw.render', () => { console.log('Map render triggered by Draw'); }); ``` -------------------------------- ### Include Mapbox GL Draw CSS via CDN Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/README.md Include the Mapbox GL Draw CSS file using a CDN link in your HTML. ```html ``` -------------------------------- ### this.select Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/MODES.md Adds a feature to the draw's internal selection state. ```APIDOC ## this.select ### Description Add a feature to draw's internal selected state ### Parameters #### Path Parameters - **id** (String) - ``` -------------------------------- ### Configure draw_line_string mode options Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md When changing to 'draw_line_string' mode, you can provide options to continue drawing an existing LineString from a specific point. ```javascript { // The id of the LineString to continue drawing featureId: string, // The point to continue drawing from from: Feature|Point|Array } ``` -------------------------------- ### Handle draw.create event Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md Listen for the 'draw.create' event to access newly created features. This event fires when a feature drawing is completed. ```javascript map.on('draw.create', function (e) { console.log(e.features); }); ``` -------------------------------- ### changeMode(mode, options?) Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md Changes the Draw instance to a different mode, optionally with specific options. Returns the draw instance for chaining. ```APIDOC ## changeMode(mode, options?) ### Description Transitions the Draw instance to a specified mode. Certain modes accept an `options` object to configure the mode upon entry. ### Method `draw.changeMode(mode: string, options?: Object)` ### Parameters #### Path Parameters - `mode` (string) - Required - The name of the mode to change to. - `options` (Object) - Optional - Configuration options for specific modes. - `simple_select` mode options: - `featureIds` (Array) - Array of feature IDs to be initially selected. - `direct_select` mode options: - `featureId` (string) - The ID of the feature to be directly selected. - `draw_line_string` mode options: - `featureId` (string) - The ID of the LineString to continue drawing. - `from` (Feature|Point|Array) - The point to continue drawing from. ### Returns - `draw` - The draw instance for chaining. ``` -------------------------------- ### Include Mapbox GL Draw via CDN Source: https://github.com/mapbox/mapbox-gl-draw/blob/main/README.md Include the Mapbox GL Draw JavaScript file using a CDN link in your HTML. ```html ``` -------------------------------- ### Mode Actions: trash(), combineFeatures(), uncombineFeatures() Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Perform context-sensitive actions that delegate to the current mode's behavior. These include deleting selected features, combining them into a single feature (e.g., MultiPoint), or splitting them back apart. ```javascript map.on('load', () => { const [id1] = draw.add({ type: 'Point', coordinates: [0, 0] }); const [id2] = draw.add({ type: 'Point', coordinates: [1, 1] }); // Select both points, then combine into a MultiPoint draw.changeMode('simple_select', { featureIds: [id1, id2] }); draw.combineFeatures(); console.log(draw.getAll().features[0].geometry.type); // => 'MultiPoint' // Split the MultiPoint back into individual Points draw.uncombineFeatures(); console.log(draw.getAll().features.length); // => 2 // trash() deletes selected features in simple_select, // deletes selected vertices in direct_select, // cancels drawing in draw_* modes draw.changeMode('simple_select', { featureIds: draw.getSelectedIds() }); draw.trash(); }); ``` -------------------------------- ### draw.changeMode(mode, options) Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Programmatically transitions Draw into a different interaction mode. Accepts a mode name and optional options, returning the draw instance for chaining. Use `Draw.modes` enum for mode name constants. ```APIDOC ## `draw.changeMode(mode, options)` — Change Interaction Mode `changeMode(mode: string, options?: Object) => draw` — Programmatically transitions Draw into a different mode. Returns the draw instance for chaining. Use `Draw.modes` enum for mode name constants. ### Parameters #### Path Parameters - **mode** (string) - Required - The name of the mode to change to. - **options** (Object) - Optional - Additional options for the mode. - **featureIds** (Array) - Optional - For modes like 'simple_select' or 'direct_select', specifies which features to select. - **featureId** (string) - Optional - For 'direct_select', specifies the feature to select. - **from** (Object) - Optional - For drawing modes like 'draw_line_string', specifies the starting point. ### Request Example ```js map.on('load', () => { // Start drawing a polygon draw.changeMode('draw_polygon'); // Start drawing a point draw.changeMode(MapboxDraw.modes.DRAW_POINT); // Enter simple_select with pre-selected features const [id] = draw.add({ type: 'Point', coordinates: [-74.5, 40] }); draw.changeMode('simple_select', { featureIds: [id] }); // Enter direct_select on a specific feature draw.changeMode('direct_select', { featureId: id }); // Continue drawing an existing LineString from a specific vertex const [lineId] = draw.add({ type: 'Feature', properties: {}, geometry: { type: 'LineString', coordinates: [[-74.5, 40], [-74.0, 40.5]] } }); draw.changeMode('draw_line_string', { featureId: lineId, from: { type: 'Point', coordinates: [-74.0, 40.5] } }); console.log(draw.getMode()); // => 'draw_line_string' }); ``` ``` -------------------------------- ### draw.trash() / draw.combineFeatures() / draw.uncombineFeatures() Source: https://context7.com/mapbox/mapbox-gl-draw/llms.txt Context-sensitive actions that delegate to the current mode's behavior. These methods are useful for performing operations like deleting selected features, combining selected features into a single multi-feature, or splitting a multi-feature back into its components. All return the draw instance for chaining. ```APIDOC ## `draw.trash()` / `draw.combineFeatures()` / `draw.uncombineFeatures()` — Mode Actions Context-sensitive actions that delegate to the current mode's behavior. All return the draw instance for chaining. ### Description - `trash()`: Deletes selected features in `simple_select` mode, deletes selected vertices in `direct_select` mode, or cancels drawing in `draw_*` modes. - `combineFeatures()`: Combines currently selected features into a single multi-feature geometry (e.g., a MultiPoint from multiple Points). - `uncombineFeatures()`: Splits a multi-feature geometry back into its individual constituent features. ### Request Example ```js map.on('load', () => { const [id1] = draw.add({ type: 'Point', coordinates: [0, 0] }); const [id2] = draw.add({ type: 'Point', coordinates: [1, 1] }); // Select both points, then combine into a MultiPoint draw.changeMode('simple_select', { featureIds: [id1, id2] }); draw.combineFeatures(); console.log(draw.getAll().features[0].geometry.type); // => 'MultiPoint' // Split the MultiPoint back into individual Points draw.uncombineFeatures(); console.log(draw.getAll().features.length); // => 2 // trash() deletes selected features in simple_select, // deletes selected vertices in direct_select, // cancels drawing in draw_* modes draw.changeMode('simple_select', { featureIds: draw.getSelectedIds() }); draw.trash(); }); ``` ```