Skip to content
import DirectionsViewModel from "@arcgis/core/widgets/Directions/DirectionsViewModel.js";
Inheritance:
DirectionsViewModelAccessor
Since
ArcGIS Maps SDK for JavaScript 4.6

Provides the communication and data manipulation logic for the Directions widget and component.

See also
Example
const layer = new RouteLayer();
map.add(layer);
// Create and instantiate the DirectionsViewModel with an API key and the RouteLayer.
// Use `load()` to load the view model's routing resources including the service description associated with the route layer's routing service.
const apiKey = "<your api key>";
const directionsViewModel = new DirectionsViewModel({ apiKey, layer });
await directionsViewModel.load();

Constructors

Constructor

Constructor
Parameters
ParameterTypeDescriptionRequired
properties
See the properties table for a list of all the properties that may be passed into the constructor.

Properties

Any properties can be set, retrieved or listened to. See the Watch for changes topic.

apiKey

Property
Type
string | null | undefined
Since
ArcGIS Maps SDK for JavaScript 4.19

An authorization string used to access a resource or service. API keys are generated and managed in the portal. An API key is tied explicitly to an ArcGIS account; it is also used to monitor service usage. Setting a fine-grained API key on a specific class overrides the global API key.

By default, the following URLs will be used (unless overwritten in the app, or if using different defaults from a portal):

Geocoding URL: https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer

Routing URL: https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World

autoSolve

Property
Type
boolean
Since
ArcGIS Maps SDK for JavaScript 4.32

When true, the assigned route layer will automatically solve whenever the stops or barriers (if any) are edited. The default value is true. Setting this property to false may be useful for complex routes that take a long time to solve.

Default value
true

autoSolveOn

Property
Type
AutoSolveState[]
Since
ArcGIS Maps SDK for JavaScript 5.0

When autoSolve is true, this property defines when a route will be re-solved.

When "complete" is included the route will only re-solved once the interactive operation is complete. This is normally when the selected network feature or features are deselected.

When "active" is included the route will re-solve continuously as the interactive operation is ongoing (e.g., while dragging a stop or waypoint).

By default, the route will only re-solve when the interactive operation is complete.

declaredClass

readonlyinherited Property
Type
string
Inherited from: Accessor
Since
ArcGIS Maps SDK for JavaScript 4.7

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

goToOverride

inherited Property
Type
GoToOverride | null | undefined
Inherited from: GoTo
Since
ArcGIS Maps SDK for JavaScript 4.8

This function provides the ability to override either the MapView goTo() or SceneView goTo() methods.

See also
Example
// The following snippet uses Search but can be applied to any
// widgets that support the goToOverride property.
search.goToOverride = function(view, goToParams) {
goToParams.options = {
duration: updatedDuration
};
return view.goTo(goToParams.target, goToParams.options);
};

impedanceAttribute

readonly Property
Type
NetworkAttribute | null | undefined

The network attribute name to be used as the impedance attribute in the analysis. The value is defined in the specific routing network layer used in the route.

For more information, see Understanding the network attribute.

lastRoute

readonly Property
Type
RouteLayerSolveResult | null | undefined

The most recent route result. Returns a RouteLayerSolveResult object containing properties for barriers (if any), stops, and directions.

See also

layer

Property
Type
RouteLayer | null | undefined
Since
ArcGIS Maps SDK for JavaScript 4.24

The RouteLayer associated with the DirectionsViewModel. The route layer contains stops and barriers and will be used to display and solve routes.

maxStops

Property
Type
number

The maximum number of stops allowed for routing.

Default value
50

routeParameters

autocast Property
Type
RouteParameters

Route Parameters object used to call the service. Please refer to the RouteParameters documentation for the list of available settings.

selectedTravelMode

autocast Property
Type
TravelMode | null | undefined

The travel mode that will be used by getDirections() when requesting the route and directions.

For a list of available travel modes please access travelModes or the supportedTravelModes property on the serviceDescription.

If the RouteLayer assigned to layer is hosted on ArcGIS Online and ArcGIS Enterprise then this property will attempt to assign the previously used travel mode.

By default, if the layer is not an ArcGIS Online and ArcGIS Enterprise item, this property will be to routing service's default travel mode (see defaultTravelMode of NetworkServiceDescription).

See also
Example
// Create a RouteLayer and assign to the DirectionsViewModel.
const layer = new RouteLayer();
map.add(layer);
const apiKey = "<your api key>";
const directionsViewModel = new DirectionsViewModel({ apiKey, layer });
await directionsViewModel.load(); // wait for the view model to load the route service's "service description".
// Print view model's selected travel mode. This will be equivalent to the routing service's default travel mode.
console.log(directionsViewModel.selectedTravelMode.name);
// Assign the "Walking Time" travel mode.
directionsViewModel.selectedTravelMode = directionsViewModel.travelModes.find(({ name }) => name === "Walking Time");

serviceDescription

readonly Property
Type
NetworkServiceDescription | null | undefined

The Service Description object returned by the Route REST Endpoint. This object contains three properties: currentVersion, defaultTravelMode, and supportedTravelModes.

This information is useful when implementing complex logistics scenarios operating with limitations or preferences on vehicle or stop properties, for example avoiding toll roads, dealing with hazardous materials, working with stop service times, etc.

state

readonly Property
Type
State

The current state of the view model.

Default value
"disabled"

timeAttribute

readonly Property
Type
NetworkAttribute | null | undefined

The name of the network attribute to use for the drive time when computing directions.

travelModes

readonly Property
Type
TravelMode[]

An array of available travel modes from the associated RouteLayer's routing service (see RouteLayer.url).

view

Property
Type
MapViewOrSceneView | null | undefined

The view from which the widget will operate.

Methods

MethodSignatureClass
centerAt(stopOrManeuver: Graphic | Stop | (GeometryUnion | null | undefined)): void
clearHighlights(): void
clearResults(): void
emit
inherited
emit<Type extends EventNames<this>>(type: Type, event?: this["@eventTypes"][Type]): boolean
getCostAttribute(attributeName: string): NetworkAttribute | null | undefined
getDirections(): Promise<RouteLayerSolveResult>
hasEventListener
inherited
hasEventListener<Type extends EventNames<this>>(type: Type): boolean
highlight(networkFeature: DirectionLine | DirectionPoint | PointBarrier | PolygonBarrier | PolylineBarrier | RouteInfo | Stop): Promise<void>
load(): Promise<void>
on
inherited
on<Type extends EventNames<this>>(type: Type, listener: EventedCallback<this["@eventTypes"][Type]>): ResourceHandle
reset(): void
save(): Promise<PortalItem>
saveAs(portalItem: PortalItem, options?: LayerSaveAsOptions): Promise<PortalItem>
zoomToRoute(): void

centerAt

Method
Signature
centerAt (stopOrManeuver: Graphic | Stop | (GeometryUnion | null | undefined)): void

Centers the map at the specified maneuver or stop.

Parameters
ParameterTypeDescriptionRequired
stopOrManeuver

The stop or maneuver where the map should be centered.

Returns
void

clearHighlights

Method
Signature
clearHighlights (): void

Clears any highlighted route segments.

Returns
void

clearResults

Method
Signature
clearResults (): void

Removes the route directions from the directions list, leaving the inputs untouched. The route and locations persist on the map.

Returns
void

emit

inherited Method
Signature
emit <Type extends EventNames<this>>(type: Type, event?: this["@eventTypes"][Type]): boolean
Type parameters
<Type extends EventNames<this>>
Inherited from: EventedMixin

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

Parameters
ParameterTypeDescriptionRequired
type
Type

The name of the event.

event
this["@eventTypes"][Type]

The event payload.

Returns
boolean

true if a listener was notified

getCostAttribute

Method
Signature
getCostAttribute (attributeName: string): NetworkAttribute | null | undefined

Returns the cost attribute associated with the parsed name.

Parameters
ParameterTypeDescriptionRequired
attributeName

The attribute name specifying the cost attribute used as an impedance.

Returns
NetworkAttribute | null | undefined

The cost attribute associated with the passed name.

PropertyTypeDescription
namestringName of the impedance network attribute.
unitsstringUnits of this network attribute.

getDirections

Method
Signature
getDirections (): Promise<RouteLayerSolveResult>

Computes a route and directions. If successful, results will be assigned to lastRoute and returned in a resolving promise. If a view is assigned, it will zoom to the extent of the route.

Returns
Promise<RouteLayerSolveResult>

When resolved, returns a RouteLayerSolveResult.

hasEventListener

inherited Method
Signature
hasEventListener <Type extends EventNames<this>>(type: Type): boolean
Type parameters
<Type extends EventNames<this>>
Inherited from: EventedMixin

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

Parameters
ParameterTypeDescriptionRequired
type
Type

The name of the event.

Returns
boolean

Returns true if the class supports the input event.

highlight

Method
Signature
highlight (networkFeature: DirectionLine | DirectionPoint | PointBarrier | PolygonBarrier | PolylineBarrier | RouteInfo | Stop): Promise<void>
Since
ArcGIS Maps SDK for JavaScript 4.24

Highlights the specified network feature.

Parameters
ParameterTypeDescriptionRequired
networkFeature

The network feature to highlight.

Returns
Promise<void>

Resolves when the highlight has been completed.

load

Method
Signature
load (): Promise<void>

This method should be called to load the view model's routing resources.

This method downloads service metadata from the assigned routing service. Call this method before accessing properties on the view model or whenever the layer changes.

Returns
Promise<void>

When resolved, the view model has loaded the route service metadata necessary for routing.

on

inherited Method
Signature
on <Type extends EventNames<this>>(type: Type, listener: EventedCallback<this["@eventTypes"][Type]>): ResourceHandle
Type parameters
<Type extends EventNames<this>>
Inherited from: EventedMixin

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

Parameters
ParameterTypeDescriptionRequired
type
Type

An event or an array of events to listen for.

listener
EventedCallback<this["@eventTypes"][Type]>

The function to call when the event fires.

Returns
ResourceHandle

Returns an event handler with a remove() method that should 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);
});

reset

Method
Signature
reset (): void

Resets the state of the ViewModel, clearing all the input stops and results in the widget and in the map.

Returns
void

save

Method
Signature
save (): Promise<PortalItem>
Since
ArcGIS Maps SDK for JavaScript 4.24

Saves the RouteLayer associated with the view model. This method will update the portal-item associated with layer.

See also
Returns
Promise<PortalItem>

When resolved, returns a PortalItem.

saveAs

Method
Signature
saveAs (portalItem: PortalItem, options?: LayerSaveAsOptions): Promise<PortalItem>
Since
ArcGIS Maps SDK for JavaScript 4.24

Saves the RouteLayer associated with the view model as a new portal item.

See also
Parameters
ParameterTypeDescriptionRequired
portalItem

The new portal item to which the layer will be saved.

options

Save options. Currently, there is only one property that can be set, which is folder.

Returns
Promise<PortalItem>

Saved portal item.

zoomToRoute

Method
Signature
zoomToRoute (): void

Zoom so that the full route is displayed within the current map extent.

Returns
void

Type definitions

State

Type definition
Type
"disabled" | "error" | "initializing" | "ready" | "routing" | "unauthenticated"

AutoSolveState

Type definition
Supertypes
Exclude<SketchUpdateEventState‚ "start">