SketchViewModel

AMD: require(["esri/widgets/Sketch/SketchViewModel"], (SketchViewModel) => { /* code goes here */ });
ESM: import SketchViewModel from "@arcgis/core/widgets/Sketch/SketchViewModel.js";
Class: esri/widgets/Sketch/SketchViewModel
Inheritance: SketchViewModel Accessor
Since: ArcGIS Maps SDK for JavaScript 4.5

Overview

Provides the logic for the Sketch widget. The SketchViewModel is intended to be used with Graphics and requires a GraphicsLayer to be specified in its layer property. The Sketch widget provides out-of-the box functionality with a user interface (UI). Therefore, the Sketch widget allows users to not worry about designing and creating their own UI. On the other hand, the SketchViewModel is the logic behind the Sketch widget UI, allowing users who utilize this class in their applications to design their own custom UI for the draw tools.

For example, the sample Filter SceneLayer with FeatureFilter demonstrates an example of utilizing the SketchViewModel with a custom UI.

layers-scenelayer-feature-masking

Additionally, users can pick and choose which draw tools are relevant to their applications. In this example, only the point, polyline, and polygon tools are used.

Pointer and keyboard gestures

Pointer and keyboard gestures for creating graphics with different geometries are described in the tables below.

General shortcuts

Gesture Action Example
Z Incrementally undo actions recorded in the stack. The undo/redo stack is for an individual sketch operation, meaning you can redo/undo actions while creating or updating a graphic. Undo
R Incrementally redo actions recorded in the stack. The undo/redo stack is for an individual sketch operation, meaning you can redo/undo actions while creating or updating a graphic. Redo
Ctrl Toggle snapping dependent on the configuration in snappingOptions. Ctrl key
Tab While drawing or updating features, activate the tooltips' input mode to enter values or add editing constraints. Depends on tooltipOptions configuration. Tab key

Creating point graphics

Gesture Action
Left-click Adds a point graphic at the pointer location.
Enter Adds a point graphic at the pointer location.

Creating polyline and polygon graphics

The following keyboard shortcuts apply when creating polyline and polygon graphics.

Gesture Action Example
Left-click Adds a vertex at the pointer location. Left-click
Left-drag Adds a vertex for each pointer move in hybrid or freehand mode. Left drag
F Adds a vertex to the polyline or polygon graphic. Completes the rectangle or circle polygon graphic in click mode. F vertex add
Enter Completes the polyline or polygon graphic without the staged vertex. A double-click will complete the graphic at the current mouse cursor's position. Enter
Spacebar+Left-drag Pan the view while creating a polyline or polygon graphic. Space left drag
Left-click on the first vertex Completes the polygon graphic sketch. Left-click first vertex

Creating polygon graphics with predefined shapes

The following keyboard shortcuts apply when creating polygon graphics with predefined shapes (rectangle and circle).

Gesture Action Example
Left-click+Drag Creates a rectangle graphic with dimensions based on the bounding box between initial click and cursor location. Creates a circle graphic with radius based on the distance between initial click and cursor location. Polygon Left-click drag
Shift+Left-click+Drag Changes the shape from a rectangle to a square or from a circle to an ellipse. Shift Left-click drag
Alt+Left-click+Drag Creates a rectangle graphic with a center at initial click, and dimensions based on the distance between the initial click to the cursor location. Creates a circle graphic with a radius based on the bounding box between the initial click and the cursor location. Alt Left-click drag
Shift+Alt+Left-click+Drag Combines the behavior described above. Shift Alt Left-click drag

Updating graphics

The Sketch widget provides users with the ability to move, rotate, scale or reshape graphics during an update operation. To begin updating, Left-click on a graphic. Use Shift+Left-click to add more graphics to the selection, for bulk updating. Once graphics are selected, the following actions can be performed.

Gesture Action Example
Left-click on a graphic Select a graphic to move, rotate or scale. Select a graphic
Shift+Left-click graphics Select multiple graphics to move, rotate or scale. Select graphics
Drag graphic Move the selected graphic. Drag the graphic
Drag rotate handle Rotate the selected graphic. Rotate the graphic
Drag scale handle Scale the selected graphic. Scale the graphic
Shift+Left-click+Drag scale handle Scale the selected graphic at the center. Scale the graphic at the center
Z Incrementally undo actions recorded in the stack. The undo/redo stack is for an individual sketch operation, meaning you can redo/undo actions while creating or updating a graphic. Undo update
R Incrementally redo actions recorded in the stack. The undo/redo stack is for an individual sketch operation, meaning you can redo/undo actions while creating or updating a graphic. Redo update
Left-click on view (not the graphic) Complete the graphic update. Sketch update complete
Press Delete key Remove the selected graphic(s) from the layer. Sketch delete graphic

The following update operations can be performed on a single polyline or polygon graphic:

Gesture Action Example
Left-click on a graphic Select a graphic to move or reshape. Select a graphic
Drag graphic Move the selected graphic. Drag the graphic
Left-click on a ghost vertex Add a new vertex. Add a vertex
Left-click on a vertex Select a vertex. Select a vertex
Shift+Left-click on vertices Select or unselect multiple vertices. Select vertices
Drag vertex Move the selected vertex or vertices. Drag vertices
Right-click on a vertex Delete a vertex. Delete a vertex
Select multiple vertices and press Backspace or Delete key Delete multiple vertices. Delete vertices

The following update operations can be performed on a single graphic with point geometry in a SceneView, if the graphic uses a 3D object symbol layer:

Gesture Action Example
Left-click on a graphic Select a graphic to move, rotate or scale. Select a graphic
Drag inner handle Move the selected graphic. Drag the graphic
Drag height handle Move the selected graphic vertically (on the z axis). Drag the graphic
Drag outer handle sideways Rotate the selected graphic. Rotate the graphic
Drag outer handle inwards or outwards Scale the selected graphic. Scale the graphic

Overriding Symbology

The SketchViewModel also allows users to override the default symbology for polyline, polygon, point, and multipoint graphics. The following code snippet demonstrates an example of utilizing TextSymbols to override the default point graphic symbology.

// Create a text symbol for drawing the point
const textKeySymbol = {
  type: "text", // autocasts as new TextSymbol()
  color: "#7A003C",
  text: "\ue656", // esri-icon-key
  font: {
    // autocasts as new Font()
    size: 20,
    family: "CalciteWebCoreIcons"
  }
};

const sketchViewModel = new SketchViewModel({
  view: view,
  layer: graphicsLayer,
  pointSymbol: textKeySymbol
});

The example above overrides the default symbology of a point graphic with a key icon, using the font CalciteWebCoreIcons.

It is now possible to also override the default drawing symbology while actively creating a new graphic using pointSymbol, polylineSymbol, and polygonSymbol. In earlier versions, setting these properties would only override the graphic symbology after completing the draw operation. The activeFillSymbol property allowed users to override the default drawing symbol in order to match the final polygonSymbol. This was needed for users to see what the final graphic symbol would look like while actively drawing. Setting the pointSymbol, polylineSymbol, and polygonSymbol now allows users to see what the final graphic symbol will look like while still actively drawing a graphic. The image below demonstrates the behavior when setting the polygonSymbol.

active-fill-active-line

The following is the code snippet used in the example above.

const polygonSymbol = {
  type: "simple-fill", // autocasts as new SimpleFillSymbol()
  color: "#F2BC94",
  outline: {
    // autocasts as new SimpleLineSymbol()
    color: "#722620",
    width: 3
  }
};

const sketchViewModel = new SketchViewModel({
  view: view,
  layer: graphicsLayer,
  polygonSymbol: polygonSymbol,
});

Sketch 3D

To be able to manipulate features on the z-axis using the height handle, the following configurations are relevant:

// define the GraphicsLayer
const gLayer = new GraphicsLayer({
  elevationInfo: {
    mode: "absolute-height" // default value
  }
});

// define the SketchViewModel
const sketchVM = new SketchViewModel({
  layer: gLayer,
  view: view,
  defaultCreateOptions: {
    hasZ: true  // default value
  },
  defaultUpdateOptions: {
    enableZ: true  // default value
  }
});

In absolute-height elevation mode, the sketched vertices snap to scene elements (features and ground). See elevation info for more information on how z-values are used with different elevation modes.

When sketching polygons or polylines, the elevation constraint is applied by default. This means that all vertices use the z-value of the first vertex. To unlock the elevation constraint while sketching, make sure the tooltips and their inputs are enabled, and activate the input mode with the Tab key.
Note that in elevation modes other than absolute-height, this means that the z-values are fixed but the graphic may appear non-planar.

See more about available tooltip inputs and constraints under the tooltip options class.

Known Limitation

Multipoint geometry can only be created in a MapView.

See also
Example
// Create a new SketchViewModel and set its required parameters
let sketchVM = new SketchViewModel({
  layer: tempGraphicsLayer,
  view: view
});

// Listen to sketchViewModel's create event.
sketchVM.on("create", function(event) {
  // check if the create event's state has changed to complete indicating
  // the graphic create operation is completed.
  if (event.state === "complete") {
    // remove the graphic from the layer. Sketch adds
    // the completed graphic to the layer by default.
    polygonGraphicsLayer.remove(event.graphic);

    // use the graphic.geometry to query features that intersect it
    selectFeatures(event.graphic.geometry);
  }
});

Constructors

SketchViewModel

Constructor
new SketchViewModel(properties)
Parameter
properties Object
optional

See the properties for a list of all the properties that may be passed into the constructor.

Example
// Typical usage
let sketch = new SketchViewModel({
  view: view,
  layer: graphicsLayer
});

Property Overview

Any properties can be set, retrieved or listened to. See the Working with Properties topic.
Show inherited properties Hide inherited properties
Name Type Summary Class

The SimpleFillSymbol displayed when actively creating a new polygon graphic using the polygon tool.

SketchViewModel

When creating new graphics (for example after create() has been called), this property reflects the create tool being used.

SketchViewModel

The graphic that is being created.

SketchViewModel

The name of the class.

Accessor

Default create options set for the SketchViewModel.

SketchViewModel

Default update options set for the SketchViewModel.

SketchViewModel

Options to configure the sketch labels shown next to each segment of the geometry being created or updated.

SketchViewModel

The GraphicsLayer associated with the SketchViewModel.

SketchViewModel

A SimpleMarkerSymbol, PointSymbol3D, TextSymbol, CIMSymbol, or WebStyleSymbol used for representing the point geometry that is being drawn.

SketchViewModel

A SimpleFillSymbol, PolygonSymbol3D, or CIMSymbol used for representing the polygon geometry that is being drawn.

SketchViewModel

A SimpleLineSymbol, LineSymbol3D, or CIMSymbol used for representing the polyline geometry that is being drawn.

SketchViewModel

The SnappingOptions for sketching.

SketchViewModel

The sketch view model's state.

SketchViewModel

Options to configure the tooltip shown next to the cursor when creating or updating graphics.

SketchViewModel

An array of graphics that are being updated by the SketchViewModel.

SketchViewModel

Indicates if a graphic can be selected to be updated.

SketchViewModel

Options to configure how values are displayed and input when creating or updating graphics.

SketchViewModel

The view in which geometries will be sketched by the user.

SketchViewModel

Property Details

activeFillSymbol

Property
activeFillSymbol SimpleFillSymbol
Since: ArcGIS Maps SDK for JavaScript 4.20 SketchViewModel since 4.5, activeFillSymbol added at 4.20.

The SimpleFillSymbol displayed when actively creating a new polygon graphic using the polygon tool. Only supported in 2D MapViews.

The default value is the following:

{
  type: "simple-fill",
  style: "solid",
  color: [150, 150, 150, 0.2],
  outline: {
    color: [50, 50, 50],
    width: 0
  }
}

activeTool

Property
activeTool Stringreadonly
Since: ArcGIS Maps SDK for JavaScript 4.10 SketchViewModel since 4.5, activeTool added at 4.10.

When creating new graphics (for example after create() has been called), this property reflects the create tool being used. When updating graphics (for example after update() has been called), this property reflects the update tool being used. If no create or update operation is in progress, this is null.

Possible Values:"point" |"multipoint" |"polyline" |"polygon" |"circle" |"mesh" |"rectangle" |"move" |"transform" |"reshape"

createGraphic

Property
createGraphic Graphicreadonly
Since: ArcGIS Maps SDK for JavaScript 4.10 SketchViewModel since 4.5, createGraphic added at 4.10.

The graphic that is being created.

declaredClass

Inherited
Property
declaredClass Stringreadonly
Inherited from Accessor
Since: ArcGIS Maps SDK for JavaScript 4.7 Accessor since 4.0, declaredClass added at 4.7.

The name of the class. The declared class name is formatted as esri.folder.className.

defaultCreateOptions

Property
defaultCreateOptions Object
Since: ArcGIS Maps SDK for JavaScript 4.14 SketchViewModel since 4.5, defaultCreateOptions added at 4.14.

Default create options set for the SketchViewModel.

Properties
defaultZ Number
optional

The default z-value of the newly created geometry. Ignored when hasZ is false or the layer's elevation mode is set to absolute-height.

hasZ Boolean
optional

Controls whether the created geometry has z-values or not.

mode String
optional

Create operation mode how the graphic can be created.

Value Description
hybrid Vertices are added while the pointer is clicked or dragged. Applies to polygon and polyline.
freehand Vertices are added while the pointer is dragged. Applies to polygon, polyline rectangle and circle. Default for rectangle and circle.
click Vertices are added when the pointer is clicked. Applies to polygon, polyline rectangle and circle. Default for polygon and polyline.

Possible Values:"hybrid"|"freehand"|"click"

preserveAspectRatio Boolean
optional

Controls whether or not the width and height of the drawn geometry are kept equal. Applies to rectangle and circle.

defaultUpdateOptions

Property
defaultUpdateOptions Object
Since: ArcGIS Maps SDK for JavaScript 4.10 SketchViewModel since 4.5, defaultUpdateOptions added at 4.10.

Default update options set for the SketchViewModel. Update options set on this property will be overridden by options passed to the update() method.

Properties
tool String
optional

Name of the update tool. The default tool is transform for graphics with polygon and polyline geometries and move for graphics with point and multipoint geometries. However, if a graphic with point geometry uses a 3D object symbol layer, the default tool is transform.

Possible Values:"move"|"transform"|"reshape"

enableRotation Boolean
optional
Default Value:true

Indicates if the rotation operation will be enabled when updating graphics. Only applies if tool is transform.

enableScaling Boolean
optional
Default Value:true

Indicates if the scale operation will be enabled when updating graphics. Only applies if tool is transform.

enableZ Boolean
optional
Default Value:true

Indicates if z-values can be modified when updating the graphic. When enabled, the height handle manipulator is displayed.

multipleSelectionEnabled Boolean
optional
Default Value:true

Indicates whether more than one selection can be made at once. This applies to the shift+click interaction with the transform tool.

preserveAspectRatio Boolean
optional
Default Value:false

Indicates if the uniform scale operation will be enabled when updating graphics. enableScaling must be set true when setting this property to true. Only applies if tool is transform and is always true when transforming points that use a 3D object symbol layer.

toggleToolOnClick Boolean
optional
Default Value:true

Indicates if the graphic being updated can be toggled between transform and reshape update options.

reshapeOptions Object
optional

Changes the behavior for the reshape tool. Defines the operations for edge and/or the constraints for moving a shape and/or a vertex. Only supported in 3D.

Specification
edgeOperation String
optional
Default Value:"split"

Sets the reshape operation on the edge. This affects lines and polygons. Fully supported in 3D, partially in 2D.

Value Description
none No manipulators show up on the edge. (2D and 3D)
split Manipulators show up to split edges by adding a new vertex. (2D and 3D)
offset Manipulators show up to offset the edges. (only 3D)

Possible Values:"none"|"split"|"offset"

shapeOperation String
optional
Default Value:"move"

Sets the move constraints for the whole shape. Supported in 2D and 3D

Value Description
none No move manipulator show up. (2D and 3D)
move Move manipulator show up to move in xy and in z. (2D and 3D)
move-xy Move manipulator show up to move in xy only. (only 3D)

Possible Values:"none"|"move"|"move-xy"

vertexOperation String
optional
Default Value:"move"

Sets the move constraints for the vertex. Only supported in 3D.

Value Description
move Move manipulator show up to move in xy and in z.
move-xy Move manipulator show up to move in xy only.

Possible Values:"move"|"move-xy"

highlightOptions Object
optional

Options that control when to display or hide highlights for update operations.

Specification
enabled Boolean
optional
Default Value:true

Indicates if highlighting is enabled for update operations. Only supported in 2D.

Example
// Turn off highlights for update operations
const svm = new SketchViewModel({
 view,
 defaultUpdateOptions: {
   highlightOptions: {
     enabled: false
   }
 }
});
// Turn off highlights from the update() method
const updateOptions = { tool: "reshape", highlightOptions: { enabled: false }};
svm.update(graphic, updateOptions);

labelOptions

Property
labelOptions SketchLabelOptionsautocast
Since: ArcGIS Maps SDK for JavaScript 4.24 SketchViewModel since 4.5, labelOptions added at 4.24.

Options to configure the sketch labels shown next to each segment of the geometry being created or updated.

Known Limitation

Sketch labels are currently only supported when working with a SceneView.

layer

Property
layer GraphicsLayer
Since: ArcGIS Maps SDK for JavaScript 4.6 SketchViewModel since 4.5, layer added at 4.6.

The GraphicsLayer associated with the SketchViewModel. The SketchViewModel adds new graphics to this layer or can only update graphics stored in this layer.

A SimpleMarkerSymbol, PointSymbol3D, TextSymbol, CIMSymbol, or WebStyleSymbol used for representing the point geometry that is being drawn. SimpleMarkerSymbol may also be used to symbolize point features in a SceneView. However, it is recommended you use PointSymbol3D instead.

The default value is the following:

{
  type: "simple-marker",
  style: "circle",
  size: 6,
  color: [255, 255, 255],
  outline: {
   color: [50, 50, 50],
    width: 1
  }
}

polygonSymbol

Property
polygonSymbol SimpleFillSymbol |PolygonSymbol3D |CIMSymbol

A SimpleFillSymbol, PolygonSymbol3D, or CIMSymbol used for representing the polygon geometry that is being drawn. SimpleFillSymbol may also be used to symbolize polygon features in a SceneView. However, it is recommended you use PolygonSymbol3D instead.

The default value is the following:

{
  type: "simple-fill",
  color: [150, 150, 150, 0.2],
  outline: {
    color: [50, 50, 50],
    width: 2
  }
}

polylineSymbol

Property
polylineSymbol SimpleLineSymbol |LineSymbol3D |CIMSymbol

A SimpleLineSymbol, LineSymbol3D, or CIMSymbol used for representing the polyline geometry that is being drawn. SimpleLineSymbol may also be used to symbolize polyline features in a SceneView. However, it is recommended you use LineSymbol3D instead.

The default value is the following:

{
  type: "simple-line",
  color: [130, 130, 130],
  width: 2
}

snappingOptions

Property
snappingOptions SnappingOptionsautocast
Since: ArcGIS Maps SDK for JavaScript 4.18 SketchViewModel since 4.5, snappingOptions added at 4.18.

The SnappingOptions for sketching. It supports self and feature snapping.

state

Property
state Stringreadonly

The sketch view model's state.

Possible Values:"ready" |"disabled" |"active"

Default Value:disabled

tooltipOptions

Property
tooltipOptions SketchTooltipOptionsautocast
Since: ArcGIS Maps SDK for JavaScript 4.24 SketchViewModel since 4.5, tooltipOptions added at 4.24.

Options to configure the tooltip shown next to the cursor when creating or updating graphics.

updateGraphics

Property
updateGraphics Collection<Graphic>readonly
Since: ArcGIS Maps SDK for JavaScript 4.10 SketchViewModel since 4.5, updateGraphics added at 4.10.

An array of graphics that are being updated by the SketchViewModel.

updateOnGraphicClick

Property
updateOnGraphicClick Boolean
Since: ArcGIS Maps SDK for JavaScript 4.10 SketchViewModel since 4.5, updateOnGraphicClick added at 4.10.

Indicates if a graphic can be selected to be updated. If false, graphics cannot selected to be updated. Set this property to false to add a custom hitTest logic for updating graphics.

valueOptions

Property
valueOptions SketchValueOptionsautocast
Since: ArcGIS Maps SDK for JavaScript 4.29 SketchViewModel since 4.5, valueOptions added at 4.29.

Options to configure how values are displayed and input when creating or updating graphics.

view

Property
view MapView |SceneView

The view in which geometries will be sketched by the user.

Method Overview

Show inherited methods Hide inherited methods
Name Return Type Summary Class

Adds one or more handles which are to be tied to the lifecycle of the object.

Accessor

Cancels the active operation and fires the create or update event If called in the middle of a create operation, cancel() discards the partially created graphic.

SketchViewModel

Indicates if it is possible to perform a redo() action in the current update session.

SketchViewModel

Indicates if it is possible to perform an undo() action in the current update session.

SketchViewModel

Completes the active operation and fires the create or update event and changes the event's state to complete.

SketchViewModel

Create a graphic with the geometry specified in the tool parameter.

SketchViewModel

Deletes the selected graphics used in the update workflow.

SketchViewModel

Duplicates current graphics used in the update workflow and automatically adds them to the associated layer

SketchViewModel

Emits an event on the instance.

SketchViewModel

Indicates whether there is an event listener on the instance that matches the provided event name.

SketchViewModel

Returns true if a named group of handles exist.

Accessor

Registers an event handler on the instance.

SketchViewModel

Allows creation of a graphic similar to create with the difference that the geometry can be provided directly for the graphic being created.

SketchViewModel

Incrementally redo actions recorded in the stack.

SketchViewModel

Removes a group of handles owned by the object.

Accessor

Incrementally undo actions recorded in the stack.

SketchViewModel
Promise<void>

Initializes an update operation for the specified graphic(s) and fires update event.

SketchViewModel

Method Details

addHandles

Inherited
Method
addHandles(handleOrHandles, groupKey)
Inherited from Accessor
Since: ArcGIS Maps SDK for JavaScript 4.25 Accessor since 4.0, addHandles added at 4.25.

Adds one or more handles which are to be tied to the lifecycle of the object. The handles will be removed when the object is destroyed.

// Manually manage handles
const handle = reactiveUtils.when(
  () => !view.updating,
  () => {
    wkidSelect.disabled = false;
  },
  { once: true }
);

this.addHandles(handle);

// Destroy the object
this.destroy();
Parameters
handleOrHandles WatchHandle|WatchHandle[]

Handles marked for removal once the object is destroyed.

groupKey *
optional

Key identifying the group to which the handles should be added. All the handles in the group can later be removed with Accessor.removeHandles(). If no key is provided the handles are added to a default group.

cancel

Method
cancel()
Since: ArcGIS Maps SDK for JavaScript 4.10 SketchViewModel since 4.5, cancel added at 4.10.

Cancels the active operation and fires the create or update event If called in the middle of a create operation, cancel() discards the partially created graphic.

canRedo

Method
canRedo(){Boolean}

Indicates if it is possible to perform a redo() action in the current update session.

Returns
Type Description
Boolean Returns true if there is a redo action recorded in the stack.

canUndo

Method
canUndo(){Boolean}

Indicates if it is possible to perform an undo() action in the current update session.

Returns
Type Description
Boolean Returns true if there is an undo action recorded in the stack.

complete

Method
complete()
Since: ArcGIS Maps SDK for JavaScript 4.6 SketchViewModel since 4.5, complete added at 4.6.

Completes the active operation and fires the create or update event and changes the event's state to complete. If called in the middle of a create operation, complete() finishes the active create operation and keeps the valid geometry.

create

Method
create(tool, createOptions)

Create a graphic with the geometry specified in the tool parameter. When the first vertex of the graphic is added, the create event will start firing. The provided tool will become the activeTool.

Parameters
Specification
tool String

Name of the create tool. Specifies the geometry for the graphic to be created.

Possible Values:"point"|"multipoint"|"polyline"|"polygon"|"rectangle"|"circle"|"mesh"

createOptions Object
optional

Options for the graphic to be created.

Specification
defaultZ Number
optional

The default z-value of the newly created geometry. Ignored when hasZ is false or the layer's elevation mode is set to absolute-height.

hasZ Boolean
optional

Controls whether the created geometry has z-values or not.

mode String
optional

Specifies how the graphic can be created. The create mode applies only when creating polygon, polyline, rectangle and circle geometries.

Value Description
hybrid Vertices are added while the pointer is clicked or dragged. Applies to polygon and polyline.
freehand Vertices are added while the pointer is dragged. Applies to polygon, polyline rectangle and circle. Default for rectangle and circle.
click Vertices are added when the pointer is clicked. Applies to polygon, polyline rectangle and circle. Default for polygon and polyline.

Possible Values:"hybrid"|"freehand"|"click"

preserveAspectRatio Boolean
optional

Controls whether or not the width and height of the drawn geometry are kept equal. Applies to rectangle and circle.

Example
// Call create method to create a polygon with freehand option.
sketchVM.create("polygon", {mode: "freehand"});

// listen to create event, only respond when event's state changes to complete
sketchVM.on("create", function(event) {
  if (event.state === "complete") {
    // remove the graphic from the layer associated with the sketch widget
    // instead use the polygon that user created to query features that
    // intersect it.
    polygonGraphicsLayer.remove(event.graphic);
    selectFeatures(event.graphic.geometry);
  }
});

// create a square
sketchVM.create("rectangle", { preserveAspectRatio: true });

// create an ellipse
sketchVM.create("circle", { preserveAspectRatio: false });

delete

Method
delete()
Since: ArcGIS Maps SDK for JavaScript 4.14 SketchViewModel since 4.5, delete added at 4.14.

Deletes the selected graphics used in the update workflow. Calling this method will fire the delete event.

Example
// selected graphics can be deleted only when update event becomes active
sketch.on("update", function(event) {
  if (event.state === "active") {
    sketch.delete();
  }
});

// fires after delete method is called
// returns references to deleted graphics.
sketch.on("delete", function(event) {
  event.graphics.forEach(function(graphic){
    console.log("deleted", graphic)
  });
});

duplicate

Method
duplicate()
Since: ArcGIS Maps SDK for JavaScript 4.26 SketchViewModel since 4.5, duplicate added at 4.26.

Duplicates current graphics used in the update workflow and automatically adds them to the associated layer

emit

Method
emit(type, event){Boolean}

Emits an event on the instance. This method should only be used when creating subclasses of this class.

Parameters
type String

The name of the event.

event Object
optional

The event payload.

Returns
Type Description
Boolean true if a listener was notified

hasEventListener

Method
hasEventListener(type){Boolean}

Indicates whether there is an event listener on the instance that matches the provided event name.

Parameter
type String

The name of the event.

Returns
Type Description
Boolean Returns true if the class supports the input event.

hasHandles

Inherited
Method
hasHandles(groupKey){Boolean}
Inherited from Accessor
Since: ArcGIS Maps SDK for JavaScript 4.25 Accessor since 4.0, hasHandles added at 4.25.

Returns true if a named group of handles exist.

Parameter
groupKey *
optional

A group key.

Returns
Type Description
Boolean Returns true if a named group of handles exist.
Example
// Remove a named group of handles if they exist.
if (obj.hasHandles("watch-view-updates")) {
  obj.removeHandles("watch-view-updates");
}

on

Method
on(type, listener){Object}

Registers an event handler on the instance. Call this method to hook an event with a listener.

Parameters

An event or an array of events to listen for.

listener Function

The function to call when the event fires.

Returns
Type Description
Object Returns an event handler with a remove() method that should be called to stop listening for the event(s).
Property Type Description
remove Function When called, removes the listener from the event.
Example
view.on("click", function(event){
  // event is the event handle returned after the event fires.
  console.log(event.mapPoint);
});

place

Method
place(geometry)

Allows creation of a graphic similar to create with the difference that the geometry can be provided directly for the graphic being created. Placement is then done through mouse interaction.

Currently only mesh placement is supported.

The create event will start firing. A create tool will become the activeTool till placement finished.

Parameter
geometry Mesh

Geometry to place when creating the graphic. Currently only mesh geometry is supported.

Example
// create mesh at the global origin
const box = Mesh.createBox(new Point({x: 0, y: 0, z: 0, spatialReference: SpatialReference.WGS84});

// Call place method to place a mesh - this will allow the user to place the mesh using the mouse
sketchVM.place();

// listen to create event, only respond when event's state changes to complete
sketchVM.on("create", function(event) {
  if (event.state === "complete") {
    // retrieve the final position of the mesh which was chosen by the user
   const mesh = event.graphic.geometry;
   const placedLocation = mesh.origin;
  }
});

redo

Method
redo()
Since: ArcGIS Maps SDK for JavaScript 4.9 SketchViewModel since 4.5, redo added at 4.9.

Incrementally redo actions recorded in the stack. Calling this method will fire the redo event. The undo/redo stack is for an individual sketch operation, meaning you can redo/undo actions while creating or updating a graphic.

removeHandles

Inherited
Method
removeHandles(groupKey)
Inherited from Accessor
Since: ArcGIS Maps SDK for JavaScript 4.25 Accessor since 4.0, removeHandles added at 4.25.

Removes a group of handles owned by the object.

Parameter
groupKey *
optional

A group key or an array or collection of group keys to remove.

Example
obj.removeHandles(); // removes handles from default group

obj.removeHandles("handle-group");
obj.removeHandles("other-handle-group");

undo

Method
undo()
Since: ArcGIS Maps SDK for JavaScript 4.9 SketchViewModel since 4.5, undo added at 4.9.

Incrementally undo actions recorded in the stack. Calling this method will fire the undo event. The undo/redo stack is for an individual sketch operation, meaning you can redo/undo actions while creating or updating a graphic.

update

Method
update(graphics, updateOptions){Promise<void>}
Since: ArcGIS Maps SDK for JavaScript 4.10 SketchViewModel since 4.5, update added at 4.10.

Initializes an update operation for the specified graphic(s) and fires update event.

Parameters
Specification
graphics Graphic|Graphic[]

A graphic or an array of graphics to be updated. Only graphics added to SketchViewModel's layer property can be updated.

updateOptions Object
optional

Update options for the graphics to be updated.

Specification
tool String
optional

Name of the update tool. Specifies the update operation for the selected graphics. The provided tool will become the activeTool.

Possible Values

Value Description
transform This is the default tool for graphics with a polygon geometry, polyline geometry or graphics that use a 3D object symbol layer with a point geometry. It allows one or multiple graphics to be scaled, rotated and moved by default. Its default behavior can be changed by setting the enableRotation, enableScaling or preserveAspectRatio arguments when calling the update method or setting them on the defaultUpdateOptions property when the Sketch widget initializes.
reshape This tool allows the entire graphic or individual vertices of the graphic to be moved. Vertices can be added or removed. This tool can only be used with a single graphic that has a polygon or polyline geometry.
move This is the default tool for graphics with a point geometry that do not use a 3D object symbol layer. It should be used for specific cases where you just want to move selected polygon and polyline graphics without additional options. Additionally, the move tool does not support toggling to different modes, since the move operation is built into both the transform and reshape tools by default.

Possible Values:"transform"|"reshape"|"move"

enableRotation Boolean
optional
Default Value: true

Indicates if the rotation operation will be enabled when updating graphics. Only applies if tool is transform.

enableScaling Boolean
optional
Default Value: true

Indicates if the scale operation will be enabled when updating graphics. Only applies if tool is transform.

enableZ Boolean
optional
Default Value: true

Indicates if z-values can be modified when updating the graphic. When enabled, the height handle manipulator is displayed.

multipleSelectionEnabled Boolean
optional
Default Value: true

Indicates whether more than one selection can be made at once. This applies to the shift+click interaction with the transform tool.

preserveAspectRatio Boolean
optional
Default Value: false

Indicates if the uniform scale operation will be enabled when updating graphics. enableScaling must be set true when setting this property to true. Only applies if tool is transform and is always true when transforming points that use a 3D object symbol layer.

toggleToolOnClick Boolean
optional
Default Value: true

Indicates if the graphic being updated can be toggled between transform and reshape update options.

Returns
Type Description
Promise<void> Resolves when the requested update tool has been loaded and is ready to use.
Examples
// start update operation for the selected graphic
// with transform tool. Only allow uniform scaling operation.
sketchVM.update([selectedGraphic], {
  tool: "transform",
  enableRotation: false,
  enableScaling: true,
  preserveAspectRatio: true,
  toggleToolOnClick: false
});
// Listen to sketch's update event to validate graphic's
// location while it is being reshaped or moved
sketchViewModel.on("update", onGraphicUpdate);
function onGraphicUpdate(event) {
  // get the graphic as it is being updated
  const graphic = event.graphics[0];
  // check if the graphic is intersecting school buffers
  intersects = geometryEngine.intersects(buffers, graphic.geometry);

  // change the graphic symbol to valid or invalid symbol
  // depending the graphic location
  graphic.symbol = (intersects) ? invalidSymbol : validSymbol

  // check if the update event's the toolEventInfo.type is move-stop or reshape-stop
  // user finished moving or reshaping the graphic, call complete method.
  // This changes update event state to complete.
  const toolType = event.toolEventInfo.type;
  if (event.toolEventInfo && (toolType === "move-stop" || toolType === "reshape-stop")) {
    if (!intersects) {
      sketchViewModel.complete();
    }
  } else if (event.state === "complete") {
      // graphic update has been completed
      // if the graphic is in a bad spot, call sketch's update method again
      // giving user a chance to correct the location of the graphic
      if ((!contains) || (intersects)) {
        sketchViewModel.update([graphic], {
          tool: "reshape",
          toggleToolOnClick: false
        });
      }
  }
}

Event Overview

Name Type Summary Class
{graphic: Graphic,state: "start"|"active"|"complete"|"cancel",tool: "point"|"multipoint"|"polyline"|"polygon"|"rectangle"|"circle"|"mesh",toolEventInfo: CreateToolEventInfo,type: "create"}

Fires when a user starts sketching a graphic, is actively sketching a graphic and completes sketching a graphic.

SketchViewModel
{graphics: Graphic[],tool: "move"|"reshape"|"transform",type: "delete"}

Fires when a user deletes selected graphics by clicking the Delete feature button on the Sketch widget or when delete() method is called.

SketchViewModel
{graphics: Graphic[],tool: "point"|"multipoint"|"polyline"|"polygon"|"rectangle"|"circle"|"mesh"|"move"|"transform"|"reshape",type: "redo"}

Fires in response to redo action during creation of a new graphic or updating existing graphics.

SketchViewModel
{graphics: Graphic[],tool: "point"|"multipoint"|"polyline"|"polygon"|"rectangle"|"circle"|"mesh"|"move"|"transform"|"reshape",type: "undo"}

Fires in response to undo action during creation of a new graphic or updating existing graphics.

SketchViewModel
{graphics: Graphic[],state: "start"|"active"|"complete",aborted: Boolean,tool: "move"|"transform"|"reshape",type: "update",toolEventInfo: UpdateToolEventInfo}

Fires when the user starts updating graphics, is actively updating graphics, and completes updating graphics.

SketchViewModel

Event Details

create

Event
create
Since: ArcGIS Maps SDK for JavaScript 4.10 SketchViewModel since 4.5, create added at 4.10.

Fires when a user starts sketching a graphic, is actively sketching a graphic and completes sketching a graphic.

Properties
graphic Graphic

The graphic that is being created.

state String

The current state of the event.

Possible Values

Value Description
start State changes to start when the first vertex is created. Not applicable when creating points.
active State is active while graphic is being created. Not applicable when creating points.
complete State changes to complete after the complete() method is called, when the user double clicks, presses the Enter key or clicks the first vertex of the polygon while creating a graphic. When point is created, the create event is fired with the complete state.
cancel State changes to cancel if the user pressed the escape key or create() or cancel() methods are called during the create operation and before the state changes to complete.

Possible Values:"start"|"active"|"complete"|"cancel"

tool String

Name of the create tool.

Possible Values:"point"|"multipoint"|"polyline"|"polygon"|"rectangle"|"circle"|"mesh"

toolEventInfo CreateToolEventInfo

Returns additional information associated with the create operation such as where the user is clicking the view or where the user is moving the cursor to. Value of this parameter changes to null when the create event's state changes to complete or cancel.

type String

The type of the event.

The value is always "create".

Example
// Listen to sketch widget's create event.
sketchVM.on("create", function(event) {
  // check if the create event's state has changed to complete indicating
  // the graphic create operation is completed.
  if (event.state === "complete") {
    // remove the graphic from the layer. Sketch adds
    // the completed graphic to the layer by default.
    polygonGraphicsLayer.remove(event.graphic);

    // use the graphic.geometry to query features that intersect it
    selectFeatures(event.graphic.geometry);
  }
});

delete

Event
delete
Since: ArcGIS Maps SDK for JavaScript 4.14 SketchViewModel since 4.5, delete added at 4.14.

Fires when a user deletes selected graphics by clicking the Delete feature button on the Sketch widget or when delete() method is called.

Properties
graphics Graphic[]

An array of deleted graphics.

tool String

Name of the tool that was active when graphics are deleted.

Possible Values:"move"|"reshape"|"transform"

type String

The type of the event.

The value is always "delete".

redo

Event
redo
Since: ArcGIS Maps SDK for JavaScript 4.10 SketchViewModel since 4.5, redo added at 4.10.

Fires in response to redo action during creation of a new graphic or updating existing graphics. The undo/redo stack is for an individual sketch operation, meaning you can redo/undo actions while creating or updating a graphic.

Properties
graphics Graphic[]

An array of graphics that are being updated or created.

tool String

Name of the create or update tool that is active.

Possible Values:"point"|"multipoint"|"polyline"|"polygon"|"rectangle"|"circle"|"mesh"|"move"|"transform"|"reshape"

type String

The type of the event.

The value is always "redo".

undo

Event
undo
Since: ArcGIS Maps SDK for JavaScript 4.10 SketchViewModel since 4.5, undo added at 4.10.

Fires in response to undo action during creation of a new graphic or updating existing graphics. The undo/redo stack is for an individual sketch operation, meaning you can redo/undo actions while creating or updating a graphic.

Properties
graphics Graphic[]

An array of graphics that are being updated or created.

tool String

Name of the create or update tool that is active.

Possible Values:"point"|"multipoint"|"polyline"|"polygon"|"rectangle"|"circle"|"mesh"|"move"|"transform"|"reshape"

type String

The type of the event.

The value is always "undo".

update

Event
update
Since: ArcGIS Maps SDK for JavaScript 4.10 SketchViewModel since 4.5, update added at 4.10.

Fires when the user starts updating graphics, is actively updating graphics, and completes updating graphics.

Properties
graphics Graphic[]

An array of graphics that are being updated.

state String

The state of the event.

Possible Values

Value Description
start State changes to start when a graphic is selected to be updated.
active State is active while graphics are being updated and toolEventInfo parameter is not null.
complete State changes to complete after graphics are updated.

Possible Values:"start"|"active"|"complete"

aborted Boolean

Indicates if the update operation was aborted. Set to true if the user pressed the escape key, or when the update(), create() or cancel() method is called before the update event's state changes to complete.

tool String

Name of the update operation tool.

Possible Values:"move"|"transform"|"reshape"

type String

The type of the event.

The value is always "update".

toolEventInfo UpdateToolEventInfo

Update operation tool info. Returns additional information associated with the update operation that is taking place for selected graphics and what stage it is at. Value of this parameter changes to null when the update event's state changes to complete.

Example
// Listen to SketchViewModel's update event to show relevant data in a chart
// as the graphics are being moved
sketchViewModel.on("update", onMove);

// Point graphics at the center and edge of the buffer polygon are being moved.
// Recalculate the buffer with updated geometry and run the query stats using
// the updated buffer and update the chart.
function onMove(event) {
  // If the edge graphic is moving, keep the center graphic
  // at its initial location. Only move edge graphic to resize the buffer.
  if (event.toolEventInfo && event.toolEventInfo.mover.attributes.edge) {
    const toolType = event.toolEventInfo.type;
    if (toolType === "move-start") {
      centerGeometryAtStart = centerGraphic.geometry;
    }
    // keep the center graphic at its initial location when edge point is moving
    else if (toolType === "move" || toolType === "move-stop") {
      centerGraphic.geometry = centerGeometryAtStart;
    }
  }

  // the center or edge graphic is being moved, recalculate the buffer
  const vertices = [
    [centerGraphic.geometry.x, centerGraphic.geometry.y],
    [edgeGraphic.geometry.x, edgeGraphic.geometry.y]
  ];

  // client-side stats query of features that intersect the buffer
  calculateBuffer(vertices);

  // user is clicking on the view... call update method with the center and edge graphics
  if (event.state === "complete" && !event.aborted) {
    sketchViewModel.update([edgeGraphic, centerGraphic], { tool: "move" });
  }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.