API interface
Usage
//Create a Mapmost map
var map = new mapmost.Map(mapOptions);
//Create a Draw control
var draw = new MapmostDraw(drawOptions);
This plug-in only supports use after the map is loaded, so it must be added in the load event of the map:
map.on('load', function() {
// Add the Draw control to your map
map.addControl(draw);
draw.add({ .. });
});
Parameters
| name | type | default value | description |
|---|---|---|---|
| boxSelect | Boolean | true | optionalWhether to enable the use of "shift + click + drag" to box select elements. If false, using "shift + click + drag" will zoom the area. |
| clickBuffer | Number | 2 | OptionalThe number of pixels around any feature or vertex that will respond when clicked. |
| controls | Object | optionalHide or show a single control. The name of each property is a control and the value is a Boolean value 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. | |
| defaultMode | String | simple_select | optionalDefault drawing mode. |
| displayControlsDefault | Boolean | true | optional The default value of "controls". For example, if you want all controls to be turned off by default when using specified "controls", set "displayControlsDefault: false". |
| keybindings | Boolean | true | optionalWhether to enable keyboard interaction for drawing. |
| modes | Object | true | optional Custom modes, "MapmostDraw.modes" can be used to view default values. For more information about custom modes please refer to the mode documentation. |
| styles | Array | optional Array of style objects. For more information about custom styles please refer to the Styles documentation. | |
| touchBuffer | Number | 25 | OptionalThe number of pixels around any feature or vertex that will respond when touched. |
| touchEnabled | Boolean | true | optionalWhether to enable touch interaction for drawing. |
| userProperties | Boolean | false | optionalWhether to set the attributes of the feature for style setting, and prefixed with user_, such as "["==", "user_custom_label", "Example"]" |
Drawing mode
By default, MapmostDraw comes with several modes. These modes are designed to cover the basic functionality required to create GeoJSON feature types. In addition, MapmostDraw also supports [custom modes](/mapmost_docs/webgl_en/latest/docs/plugins/Mapmost-WebGL-Draw/MODES#custom drawing modes).
Mode name strings are provided as enumerations in Draw.modes.
direct_select
Allows selecting, deleting and dragging vertices. Does not work with point features because they have no vertices.
When the user clicks on a selected line segment or vertex of a polygon, Draw will enter direct_select mode. Therefore, the direct_select pattern usually follows the simple_select pattern.
Case
Draw.modes.DIRECT_SELECT === 'direct_select'
draw_line_string
Allows drawing a LineString feature.
Case
Draw.modes.DRAW_LINE_STRING === 'draw_line_string'
draw_point
Allows drawing a point feature.
Case
Draw.modes.DRAW_POINT === 'draw_point'
draw_polygon
Allows drawing a polygon feature
Case
Draw.modes.DRAW_POLYGON === 'draw_polygon'
simple_select
Allows selecting, deleting, and dragging features. In this mode, you can change the selected status of features.
Drawing is in simple_select mode by default, and will automatically change to simple_select mode again each time the user finishes drawing features or exits direct_select mode.
Case
Draw.modes.SIMPLE_SELECT === 'simple_select'
method
add
This method can add a GeoJSON Feature, FeatureCollection or Geometry to Draw. It returns an array of ids for interacting with the added features. If a feature does not have its own id, one will be automatically generated.
Parameters
| Name | Type | Description |
|---|---|---|
| geojson | Object | RequiredGeoJson data to be added. Supported GeoJSON feature types are "Point", "LineString", "Polygon", "MultiPoint", "MultiLineString" and "MultiPolygon". |
Case
If the added feature id already exists, the existing feature will be updated and no new feature will be added.
Add an element with no specified id:
var feature = { type: 'Point', coordinates: [0, 0] };
var featureIds = draw.add(feature);
console.log(featureIds);
//=> ['some-random-string']
Add a feature with the specified id:
var feature = {
id: 'unique-id',
type: 'Feature',
properties: {},
geometry: { type: 'Point', coordinates: [0, 0] }
};
var featureIds = draw.add(feature);
console.log(featureIds)
//=> ['unique-id']
changeMode
Change the drawing mode and return to the drawing instance. The mode argument must be one of the above mode names and exist in Draw.modes.
Parameters
| Name | Type | Description |
|---|---|---|
| mode | String | RequiredThe name of the mode to switch to. |
| options | Object | RequiredOptional parameters in different modes. |
The options parameters accepted by simple_select, direct_select and draw_line_string modes are as follows:
// `simple_select` mode
{
// The array of feature ids will be selected first
featureIds: Array<string>
}
// `direct_select` mode
{
//The id of the feature will be selected directly (required)
featureId: string
}
// `draw_line_string` mode
{
// The id of the LineString that continues to be drawn
featureId: string,
//Continue drawing points
from: Feature<Point>|Point|Array<number>
}
combineFeatures
Call the combineFeatures operation of the current mode and return the drawing instance.
In simple_select mode, all selected features will be merged into a Multi* feature, as long as they have the same geometry type. For example:
- The selected feature types are LineStrings => MultiLineString
- The selected feature types are MultiLineString and LineString => MultiLineString respectively
- The selected feature types are MultiLineStrings => MultiLineString
There will be no change when selecting features of different geometry types. For example:
- Selected feature types are Point and LineString => remain unchanged
- Selected feature types are MultiLineString and MultiPoint => remain unchanged
In direct_select and draw modes, no operation is performed.
delete
Removes the feature with the specified id and returns a drawing instance.
Parameters
| Name | Type | Description |
|---|---|---|
| ids | String|Array | RequiredThe name of the mode to switch to. |
In direct_select mode, deleting features will exit the mode and revert to simple_select mode.
Case
var feature = { type: 'Point', coordinates: [0, 0] };
var ids = draw.add(feature);
draw
.delete(ids)
.getAll();
// { type: 'FeatureCollection', features: [] }
deleteAll
Remove all features and return to the drawing instance.
Case
draw.add({ type: 'Point', coordinates: [0, 0] });
draw
.deleteAll()
.getAll();
// { type: 'FeatureCollection', features: [] }
get
Returns the feature with the specified id, or undefined if no feature is found.
Parameters
| Name | Type | Description |
|---|---|---|
| featureId | String | RequiredFeature id. |
Case
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] } }
getAll
Returns a feature collection containing all features.
Case
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]
// }
// }
// ]
// }
getFeatureIdsAt
Returns an array of feature ids currently rendered at the specified point. This function allows you to obtain information from Draw using the coordinates provided by the mouse event.
Parameters
| Name | Type | Description |
|---|---|---|
| point | Object | RequiredThe coordinates of the feature in the pixel space, in the form of "{ x: number, y: number }" . |
Case
var featureIds = Draw.getFeatureIdsAt({x: 20, y: 20});
console.log(featureIds)
//=> ['top-feature-at-20-20', 'another-feature-at-20-20']
getMode
Returns the current drawing mode.
getSelected
Returns a feature collection of all currently selected features.
getSelectedIds
Returns an array of ids of all currently selected features.
getSelectedPoints
Returns a collection of features for all currently selected vertices.
set
Sets the features in Draw to the specified feature collection.
This function performs the necessary delete, create, and update operations to match the features in the Draw to the specified FeatureCollection. In fact, it has the same effect as calling Draw.deleteAll() first and then calling Draw.add(featureCollection), but it has a smaller impact on performance.
Parameters
| Name | Type | Description |
|---|---|---|
| featureCollection | FeatureCollection | RequiredThe feature collection to be specified. |
Case
var ids = draw.set({
type: 'FeatureCollection',
features: [{
type: 'Feature',
properties: {},
id: 'example-id',
geometry: { type: 'Point', coordinates: [0, 0] }
}]
});
// ['example-id']
setFeatureProperty
Sets the attribute value of the feature with the specified id and returns the drawing instance. This is helpful if you use Draw’s functionality as the primary data store in your application.
Parameters
| Name | Type | Description |
|---|---|---|
| featureId | String | RequiredFeature id. |
| value | Any | RequiredAttribute value. |
trash
Call the trash operation of the current mode and return the drawing instance.
- In
simple_selectmode, all selected features are deleted. - In
direct_selectmode, all selected vertices are deleted. - In draw mode, drawing is canceled and reverts to
simple_selectmode. - If you want to delete functionality regardless of the current mode, use the
deleteordeleteAllmethod.
uncombineFeatures
Call the uncombineFeatures operation of the current mode, returning the drawing instance.
In simple_select mode, this will split each selected Multi* feature into its constituent feature parts, leaving non-Multi features unchanged. For example:
- The selected feature is composed of two parts MultiLineString => LineString, LineString
- The selected feature is MultiLineStrings consisting of three parts => LineString, LineString, LineString
- The selected feature is a MultiLineString consisting of two parts and a Point => LineString, LineString, Point
- The selected feature is LineString => LineString
In direct_select and draw modes, no operation is performed.
event
Draw triggers many events, so these events are named draw. and are emitted from the Mapmost map map object. All events are triggered by user interaction.
Case
map.on('draw.create', function (e) {
console.log(e.features);
});
If you call a function in the Draw API programmatically, no events directly corresponding to that function will be fired. For example, if you call draw.delete(), there will be no corresponding draw.delete() event because you already know what you did. However, events may be triggered later, but these events do not directly correspond to the function being called. For example, if you select a feature and then call draw.changeMode('draw_polygon') , you will not see a draw.modechange event (because it corresponds directly to the function called), but you will see a draw.selectionchange event because by changing the mode, you indirectly deselect a feature.
actionable
Triggered when Draw’s state changes (enabled/disabled). The following events will let you know whether draw.trash(), draw.combineFeatures() and draw.uncombineFeatures() will have any effect.
Case
{
actions: {
trash: true
combineFeatures: false,
uncombineFeatures: false
}
}
combine
Fires when features are merged. The following interactions will trigger this event:
- Click the Merge button when selecting multiple features in
simple_selectmode. - Call
draw.combineFeatures()when selecting multiple features insimple_selectmode.
The event data is an object of the form:
{
deletedFeatures: Array<Feature>, // Array of deleted features (those containing new features)
createdFeatures: Array<Feature> // Created multi-feature array
}
create
Fires when a feature is created. The following interactions will trigger this event:
- When you finish drawing a feature. Just click to create a point. It is only created when the user has finished drawing a LineString or Polygon and the drawn feature is valid. In other words, the drawn features will be considered complete and valid only when the user double-clicks the last vertex or presses the Enter key.
The event data is an object of the form:
{
//An array of GeoJSON objects represents the created features
features: Array<Object>
}
delete
Fires when one or more features are deleted. The following interactions will trigger this event:
- In
simple_selectmode, after selecting one or more features, click the trash button. - In
simple_selectmode, after selecting one or more features, press the Backspace or Delete key. - In
simple_selectmode, calldraw.trash()after selecting a feature.
The event data is an object of the form:
{
//An array of GeoJSON objects represents the deleted features
features: Array<Feature>
}
modechange
Fires when the mode changes. The following interactions will trigger this event:
- Click the point, line or polygon button to start drawing (enter
draw_*mode). - Finish drawing a feature (enter
simple_selectmode). - In
simple_selectmode, click on a selected feature (to enterdirect_selectmode). - In
direct_selectmode, click outside any feature (to entersimple_selectmode).
This event is fired before the current mode stops and the next mode starts. Rendering does not occur until all event handlers have fired, so you can force mode redirection by calling draw.changeMode() within the draw.modechange handler.
The event data is an object of the form:
{
mode: string //The next mode, that is, the mode to be changed when drawing
}
The simple_select and direct_select modes can be initialized with options specific to that mode (see above).
render
Triggered immediately when Draw calls setData() to update the map. This does not mean that updating the map has finished, it just means that the map is being updated.
selectionchange
Fires when the selection state changes (that is, when one or more features are selected or deselected). The following interactions will trigger this event:
- Click on a feature and select it.
- When a feature is selected, Shift-click another feature to add it to the selected features collection.
- Click on a vertex and select it.
- When a vertex is selected, Shift-click another vertex to add it to the selected vertices collection.
- Create a box-selection containing at least one feature.
- Click outside the selected features to deselect them.
- Click away from the selected vertices to deselect them.
- Finish drawing a feature (the feature is selected immediately after being drawn).
- When a feature is already selected, call
draw.changeMode()to deselect it. - Use
draw.changeMode('simple_select', { featureIds: [..] })to switch tosimple_selectmode and immediately select the specified feature. - Use
draw.delete,draw.deleteAllordraw.trashto delete features.
The event data is an object of the form:
{
features: Array<Feature> // Array of features selected after change
}
uncombine
Fires when features are not merged. The following interactions will trigger this event:
- In
simple_selectmode, when one or more multifeatures are selected, click theuncombinebutton. Non-multifeatures can also be selected. - In
simple_selectmode, when one or more multifeatures are selected, thedraw.uncombineFeatures()event is called.
The event data is an object of the form:
{
deletedFeatures: Array<Object>, // Array of deleted features (split into features)
createdFeatures: Array<Object> // Array of created features
}
update
Fires when one or more features are updated. The following interactions will trigger this event and can be broken down by action:
action: 'move'- In
simple_selectmode, completes moving one or more selected features. This event is only fired when the movement is complete (i.e. when the user releases the mouse button or clicks Enter).
- In
action: 'change_coordinates'- In
direct_selectmode, completes moving one or more selected vertices. This event is fired only when the movement is complete (i.e. when the user releases the mouse button or clicks Enter or the mouse leaves the map container). - In
direct_selectmode, deletes one or more vertices of selected features. Vertices of one or more selected features can be deleted by pressing the Backspace or Delete keys; clicking the Trash button; and calling thedraw.trash()method. - In
direct_selectmode, adds a vertex by midpointing the selected feature.
- In
This event is not fired when features are created or deleted. To track these interactions, listen to the draw.create and draw.delete events.
The event data is an object of the form:
{
features: Array<Feature>, // Update feature array
action: string //The name of the operation that triggers the update
}
Drawing style
Draw uses map styles that conform to the Mapmost GL style specification, with some caveats.
source
The GL style specification requires each layer to have a data source. However, do not provide source when setting the Draw style.
To optimize performance, Draw automatically adjusts the source of features as they are moved. Therefore, Draw will automatically provide you with a source .
The source provided by Draw is named mapmost-draw-hot and mapmost-draw-cold.
id
The GL style specification requires each layer to have an id. You must provide an id and Draw will add the suffixes .hot and .cold to your id.
In your custom style, you will need to use the following feature attributes:
| Parameter | Value | Description |
|---|---|---|
| meta | feature, midpoint, vertex | midpoint and vertex are control points used to add points on the map to represent polygons and line segments. feature is used to represent all features. |
| active | true, false | In the current mode, a feature is active when it is selected. true and false are strings. |
| mode | simple_select, direct_select, draw_point, draw_line_string, draw_polygon | Display the current mode of Draw. |
Draw also provides some other properties for features, but they should not be used for styling. For more information about these properties, see [Feature Query](/mapmost_docs/webgl_en/latest/docs/plugins/Mapmost-WebGL-Draw/API#Feature Query) below.
If opts.userProperties is set to true, the features' properties can also be used for styling. All user properties are prefixed with user_ to ensure that they do not conflict with Draw’s properties.
Custom style example
See the documentation Styles.
Feature query
Drawn with Mapmost JS’s queryRenderedFeatures.
| Name | Type | Description |
|---|---|---|
| id | String | optionalOnly available when "meta" is "feature". |
| parent | String | optionalOnly available when "meta" is not "feature". |
| coord_path | String | optionalA "." separated path pointing to the [longitude, latitude] entity in the parent coordinates. |
| lon | Number | optionalThe longitude value of the control point. Only available when "meta" is "midpoint". |
| lat | Number | optionalThe latitude value of the control point. Only available when "meta" is "midpoint". |