SketchViewModel

require(["esri/widgets/Sketch/SketchViewModel"], function(SketchViewModel) { /* code goes here */ });
Class: esri/widgets/Sketch/SketchViewModel
Inheritance: SketchViewModel Accessor
Since: ArcGIS API for JavaScript 4.5

Provides the logic for the Sketch widget.

SketchViewModel simplifies the process of adding and updating graphics on a MapView or a SceneView. SketchViewModel is intended to be used with Graphics.

Known Limitations

  • Graphics with polyline or polygon geometries can not be rotated or scaled in a SceneView.
  • Graphics with geometries where hasZ is true will be ignored by update() in a SceneView.
  • Multipoint geometry can only be created in a MapView.

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

Creating point graphics

GestureAction
Left-clickAdds a point graphic at the pointer location.
CAdds a point graphic at the pointer location.

Creating polyline and polygon graphics

GestureAction
Left-clickAdds a vertex at the pointer location.
Left-dragAdds a vertex for each pointer move.
FAdds a vertex to the polyline or polygon graphic.
CCompletes the polyline or polygon graphic sketch.
ZIncrementally undo actions recorded in the stack.
RIncrementally redo actions recorded in the stack.
Spacebar+Left-dragPan the view while creating a polyline or polygon graphic.
Left-click on the first vertexCompletes the polygon graphic sketch.

Creating polygon graphics with predefined shapes

The following keyboard shortcuts apply when creating polygon graphics with predefined shapes.

GestureAction
Left-click+DragCreates 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.
Ctrl+Left-click+DragChanges the shape from a rectangle to a square or from a circle to an ellipse.
Alt+Left-click+DragCreates 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.
Ctrl+Alt+Left-click+DragCombines the behavior described above.

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.

GestureActionExample
Left-click on a graphicSelect a graphic to move, rotate or scale.Select a graphic
Shift+Left-click graphicsSelect multiple graphics to move, rotate or scale.Select graphics
Drag graphicMove the selected graphic.Drag the graphic
Drag rotate handleRotate the selected graphic.Rotate the graphic
Drag scale handleScale the selected graphic.Scale the graphic
ZIncrementally undo actions recorded in the stack.Undo update
RIncrementally redo actions recorded in the stack.Redo update
Left-click on view (not the graphic)Complete the graphic update.Sketch update complete

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

GestureActionExample
Left-click on a graphicSelect a graphic to move or reshape.Select a graphic
Drag graphicMove the selected graphic.Drag the graphic
Left-click on a ghost vertexAdd a new vertex.Add a vertex
Left-click on a vertexSelect a vertex.Select a vertex
Ctrl+Left-click on verticesSelect or unselect multiple vertices.Select vertices
Drag vertexMove the selected vertex or vertices.Drag vertices
Right-click on a vertexDelete a vertex.Delete a vertex
Select multiple vertices and press Backspace or Delete buttonDelete 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:

GestureActionExample
Left-click on a graphicSelect a graphic to move, rotate or scale.Select a graphic
Drag inner handleMove the selected graphic.Drag the graphic
Drag outer handle sidewaysRotate the selected graphic.Rotate the graphic
Drag outer handle inwards or outwardsScale the selected graphic.Scale the graphic
See also:
Example:
// Create a new SketchViewModel and set
// its required parameters
var 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

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
var sketch = new SketchViewModel({
  view: view,
  layer: graphicsLayer
});

Property Overview

Any properties can be set, retrieved or listened to. See the Working with Properties topic.
NameTypeSummaryClass
String

Returns the name of the active tool associated with the SketchViewModel instance.

more details
more detailsSketchViewModel
Graphic

The graphic that is being created.

more details
more detailsSketchViewModel
String

The name of the class.

more details
more detailsAccessor
Object

Default update options set for the SketchViewModel.

more details
more detailsSketchViewModel
GraphicsLayer

The GraphicsLayer associated with the SketchViewModel.

more details
more detailsSketchViewModel
SimpleMarkerSymbol

A simple marker symbol used for representing the point geometry that is being drawn.

more details
more detailsSketchViewModel
SimpleFillSymbol

A simple fill symbol used for representing the polygon geometry that is being drawn.

more details
more detailsSketchViewModel
SimpleLineSymbol

A simple line symbol used for representing the polyline geometry that is being drawn.

more details
more detailsSketchViewModel
String

The sketch view model's state.

more details
more detailsSketchViewModel
Collection<Graphic>

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

more details
more detailsSketchViewModel
Boolean

Indicates if a graphic can be selected to be updated.

more details
more detailsSketchViewModel
MapView|SceneView

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

more details
more detailsSketchViewModel

Property Details

activeTool Stringreadonly
Since: ArcGIS API for JavaScript 4.10

Returns the name of the active tool associated with the SketchViewModel instance.

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

createGraphic Graphicreadonly
Since: ArcGIS API for JavaScript 4.10

The graphic that is being created.

declaredClass Stringreadonly inherited
Since: ArcGIS API for JavaScript 4.7

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

defaultUpdateOptions Object
Since: ArcGIS API for JavaScript 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.

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.

multipleSelectionEnabled Boolean
optional
Default Value:true

Indicates whether more than one selection can be made at once. This pertains to 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.

Since: ArcGIS API for JavaScript 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.

pointSymbol SimpleMarkerSymbol

A simple marker symbol used for representing the point geometry that is being drawn.

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 SimpleFillSymbol

A simple fill symbol used for representing the polygon geometry that is being drawn.

The default value is the following:

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

A simple line symbol used for representing the polyline geometry that is being drawn.

The default value is the following:

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

The sketch view model's state.

Possible Values: ready | disabled | active

updateGraphics Collection<Graphic>readonly
Since: ArcGIS API for JavaScript 4.10

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

updateOnGraphicClick Boolean
Since: ArcGIS API for JavaScript 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.

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

Method Overview

NameReturn TypeSummaryClass

Cancels the active operation and fires the create or update event and changes the event's state to cancel.

more details
more detailsSketchViewModel

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

more details
more detailsSketchViewModel

Create a graphic with a geometry specified in tool parameter.

more details
more detailsSketchViewModel
Boolean

Emits an event on the instance.

more details
more detailsSketchViewModel
Boolean

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

more details
more detailsSketchViewModel
Object

Registers an event handler on the instance.

more details
more detailsSketchViewModel

Incrementally redo actions recorded in the stack.

more details
more detailsSketchViewModel

Resets SketchViewModel to prepare for another create operation.

more details
more detailsSketchViewModel

Incrementally undo actions recorded in the stack.

more details
more detailsSketchViewModel
Promise<void>

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

more details
more detailsSketchViewModel

Method Details

cancel()
Since: ArcGIS API for JavaScript 4.10

Cancels the active operation and fires the create or update event and changes the event's state to cancel.

complete()
Since: ArcGIS API for JavaScript 4.6

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

create(tool, createOptions)

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

Parameters:
tool String

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

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

createOptions Object
optional

Options for the graphic to be created.

Specification:
mode String
optional

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

Possible Values:

ValueDescription
hybridVertices are added while the pointer is clicked or dragged. Applies to and is the default for polygon and polyline.
freehandVertices are added while the pointer is dragged. Applies to polygon, polyline rectangle and circle. Default for rectangle and circle.
clickVertices are added when the pointer is clicked.
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);
  }
});
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:
TypeDescription
Booleantrue if a listener was notified
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:
TypeDescription
BooleanReturns true if the class supports the input event.
on(type, listener){Object}

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

Parameters:

A event type, or an array of event types, to listen for.

listener Function

The function to call when the event is fired.

Returns:
TypeDescription
ObjectReturns an event handler with a remove() method that can be called to stop listening for the event(s).
PropertyTypeDescription
removeFunctionWhen 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);
});
redo()
Since: ArcGIS API for JavaScript 4.9

Incrementally redo actions recorded in the stack. Calling this method will fire the redo event.

reset()

Resets SketchViewModel to prepare for another create operation. Reset discards the current sketch, if called in middle of create operation.

undo()
Since: ArcGIS API for JavaScript 4.9

Incrementally undo actions recorded in the stack. Calling this method will fire the undo event.

update(graphics, updateOptions){Promise<void>}
Since: ArcGIS API for JavaScript 4.10

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

Parameters:
Specification:

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.

Possible Values:

ValueDescription
transformThis 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.
reshapeThis 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.
moveThis 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.
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.

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:
TypeDescription
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 === "cancel" || event.state === "complete")) {
      // graphic update has been completed or cancelled
      // 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({
          tool: "reshape",
          graphics: [graphic],
          toggleToolOnClick: false
        });
      }
  }
}

Event Overview

NameTypeSummaryClass
{graphic: Graphic,state: String,tool: String,toolEventInfo: CreateToolEventInfo,type: String}

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

more details
more detailsSketchViewModel
{graphics: Graphic[],tool: String,type: String}

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

more details
more detailsSketchViewModel
{graphics: Graphic[],tool: String,type: String}

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

more details
more detailsSketchViewModel
{graphics: Graphic[],state: String,tool: String,type: String,toolEventInfo: UpdateToolEventInfo}

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

more details
more detailsSketchViewModel

Event Details

create
Since: ArcGIS API for JavaScript 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:

ValueDescription
startState changes to start when the first vertex is created. Not applicable when creating points.
activeState is active while graphic is being created. Not applicable when creating points.
completeState changes to complete after the complete() method is called, when the user double clicks, presses the C 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.
cancelState changes to cancel if the create() or reset() methods are called during the create operation and before the state changes to complete.
tool String

Name of the create tool.

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

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. For this event, the type 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);
  }
});
redo
Since: ArcGIS API for JavaScript 4.10

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

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 | move | transform | reshape

type String

The type of the event. For this event, the type is always redo.

undo
Since: ArcGIS API for JavaScript 4.10

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

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 | move | transform | reshape

type String

The type of the event. For this event, the type is always undo.

update
Since: ArcGIS API for JavaScript 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:

ValueDescription
startState changes to start when a graphic is selected to be updated.
activeState is active while graphics are being updated and toolEventInfo parameter is not null.
completeState changes to complete after graphics are updated.
cancelState changes to cancel when graphics are selected and then unselected without any updates, or when the update, create or reset 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. For this event, the type 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 === "cancel" || event.state === "complete")) {
    sketchViewModel.update({
      tool: "move",
      graphics: [edgeGraphic, centerGraphic]
    });
  }
}

API Reference search results

NameTypeModule
Loading...