Programming patterns

Introduction

This section discusses programming patterns and best practices for writing applications with the ArcGIS Maps SDK for JavaScript.

Loading classes

After getting the ArcGIS Maps SDK for JavaScript, use require() to asynchronously load ArcGIS Maps SDK for JavaScript classes into an application.

The method requires two parameters:

  • An array of ordered strings as the full namespaces for each imported API class
  • Each API class is loaded as the positional arguments in a callback function

For example, to load the Map and MapView class, first go to the documentation and find the full namespace for each class. In this case, Map has the namespace "esri/Map" and the namespace for MapView is "esri/views/MapView". Then pass these strings as an array to require(), and use the local variable names Map and MapView as the positional arguments for the callback function:

Use dark colors for code blocksCopy
1
2
3
require(["esri/Map", "esri/views/MapView"], (Map, MapView) => {
  // The application logic using `Map` and `MapView` goes here
});

Not every module needs to be loaded with require(), as many classes can be initialized from within a constructor using autocasting.

Constructors

All classes in the ArcGIS Maps SDK for JavaScript have a single constructor, and all properties can be set by passing parameters to the constructor.

For example, here is an example of calling the constructor for the Map and MapView classes.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
const map = new Map({
  basemap: "topo-vector"
});

const view = new MapView({
  map: map,
  container: "map-div",
  center: [ -122, 38 ],
  scale: 5
});

Alternatively, the properties of class instances can be specified directly using setters.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
const map = new Map();
const view = new MapView();

map.basemap = "topo-vector";           // Set a property

const viewProps = {                    // Object with property data
  container: "map-div",
  map: map,
  scale: 5000,
  center: [ -122, 38 ]
};

view.set(viewProps);                   // Use a setter

Properties

The ArcGIS Maps SDK for JavaScript supports a simple, consistent way of getting and setting all properties of a class.

Many API classes are subclasses of the Accessor class, which defines the following methods.

Method NameReturn TypeDescription
get(propertyName)VariesGets the value of the property with the name propertyName
set(propertyFields)N/AFor each key/value pair in propertyFields, this method sets the value of the property with the name key to value

Getters

The get method returns the value of a named property.

This method is a convenience method because, without using get(), to return the value nested properties, e.g., to return the title of the property basemap of a Map object, requires an if statement to check whether basemap is either undefined or null.

Use dark colors for code blocksCopy
1
2
3
4
const basemapTitle = null;
if (map.basemap) {                     // Make sure `map.basemap` exists
  basemapTitle = map.basemap.title;
}

The get method removes the need for the if statement, and returns the value of map.basemap.title if map.basemap exists, and null otherwise.

Use dark colors for code blocksCopy
1
const basemapTitle = map.get("basemap.title");

Setters

The values of properties may be set directly.

Use dark colors for code blocksCopy
1
2
3
view.center = [ -100, 40 ];
view.zoom = 6;
map.basemap = "oceans";

When several property values need to be changed, set() can be passed a JavaScript Object with the property names and the new values.

Use dark colors for code blocksCopy
1
2
3
4
5
6
const newViewProperties = {
  center: [ -100, 40 ],
  zoom: 6
};

view.set(newViewProperties);

Watching for property changes

The API provides a utility for monitoring when property values change: reactiveUtils.

reactiveUtils

reactiveUtils provides the ability to track changes in API properties with a variety of different data types and structures, such as strings, booleans, arrays, collections, and objects. The module also allows for combining properties from multiple sources. It includes the following methods: watch(), on(), once(), when(), and whenOnce().

reactiveUtils provide TypeScript type checking. You can access properties, build objects or perform other calculations and it is all properly checked by the TypeScript compiler. Callback parameters are also correctly inferred from the getValue function.

One of the most common implementation patterns is tracking when simple properties get accessed. The pattern uses the watch() method and looks like this:

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
const handle = reactiveUtils.watch(
  // getValue function
  () => object.value,
  // Callback function
  (newValue, oldValue) => {
    console.log("New value: ", newValue, "Old value: ", oldValue);
  },
  // Optional parameters
  {
    initial: true
  }
);

The watch() method returns a WatchHandle. To stop watching for changes, call the remove() method on the watch handle, for example handle.remove(). It is a best practice to remove watchers when they are no longer needed.

Use dark colors for code blocksCopy
1
handle.remove();

The next code snippet uses watch() to track when the view.updating boolean property is accessed:

Use dark colors for code blocksCopy
1
2
3
4
5
6
const handle = reactiveUtils.watch(
  () => view.updating,
  (updating) => {
    console.log(`View is updating: ${updating}`);
  }
);

This code snippet determines if all layers become visible or not using the map.allLayers property, which is a Collection:

Use dark colors for code blocksCopy
1
2
3
4
5
6
const handle = reactiveUtils.watch(
  () => view.map.allLayers.every((layer) => layer.visible),
  (allVisible) => {
      console.log(`All layers are visible = ${allVisible}`);
  }
);

The following code snippet shows how to track when two different properties (view.stationary and view.zoom) are accessed using the watch() method:

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
const handle = reactiveUtils.watch(
  () => [view.stationary, view.zoom],
  ([stationary, zoom]) => {
    // Only print the new zoom value when the view is stationary
    if(stationary){
      console.log(`Change in zoom level: ${zoom}`);
    }
   }
);

With reactiveUtils you can track objects through the use of dot notation (e.g. object.property), as well as bracket notation (e.g. object["property"]), and through optional chaining (e.g. object.value?.property).

For example, you could track when a 3D application shows an atmosphere:

Use dark colors for code blocksCopy
1
2
3
4
5
6
const handle = reactiveUtils.watch(
 () => view.environment?.atmosphereEnabled,
 (newValue) => {
     console.log(`Atmosphere enabled = ${newValue}`);
 }
);

Autocasting

Autocasting casts JavaScript objects as ArcGIS Maps SDK for JavaScript class types without the need for these classes to be explicitly imported by the app developer.

In the following code sample, five API classes are needed to create a SimpleRenderer for a FeatureLayer.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
require([
  "esri/Color",
  "esri/symbols/SimpleLineSymbol",
  "esri/symbols/SimpleMarkerSymbol",
  "esri/renderers/SimpleRenderer",
  "esri/layers/FeatureLayer",
], (
  Color, SimpleLineSymbol, SimpleMarkerSymbol, SimpleRenderer, FeatureLayer
) => {

  const layer = new FeatureLayer({
    url: "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/WorldCities/FeatureServer/0",
    renderer: new SimpleRenderer({
      symbol: new SimpleMarkerSymbol({
        style: "diamond",
        color: new Color([255, 128, 45]),
        outline: new SimpleLineSymbol({
          style: "dash-dot",
          color: new Color([0, 0, 0])
        })
      })
    })
  });

});

With autocasting, you don't have to import renderer and symbol classes; the only module you need to import is esri/layers/FeatureLayer.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
require([ "esri/layers/FeatureLayer" ], (FeatureLayer) => {

  const layer = new FeatureLayer({
    url: "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/WorldCities/FeatureServer/0",
    renderer: {                        // autocasts as new SimpleRenderer()
      symbol: {                        // autocasts as new SimpleMarkerSymbol()
        type: "simple-marker",
        style: "diamond",
        color: [ 255, 128, 45 ],       // autocasts as new Color()
        outline: {                     // autocasts as new SimpleLineSymbol()
          style: "dash-dot",
          color: [ 0, 0, 0 ]           // autocasts as new Color()
        }
      }
    }
  });

});

To know whether a class can be autocasted, look at the ArcGIS Maps SDK for JavaScript reference for each class. If a property can be autocasted, the following image will appear:

autocast label

For example, the documentation for the property renderer of the FeatureLayer class has an autocast tag.

Notice the code using autocasting is simpler and is functionally identical to the above code snippet where all the modules are explicitly imported. The ArcGIS Maps SDK for JavaScript will take the values passed to the properties in the constructor and instantiate the typed objects internally.

Keep in mind there is no need to specify the type on properties where the module type is known, or fixed. For example, look at the outline property in the SimpleMarkerSymbol class from the snippet above. It doesn't have a type property because the only Symbol subclass with an outline property is SimpleLineSymbol.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
const diamondSymbol = {
  type: "simple-marker",
  outline: {
    type: "simple-line", // Not needed, as type `simple-line` is implied
    style: "dash-dot",
    color: [ 255, 128, 45 ]
  }
};

In cases where the type is more generic, such as FeatureLayer.renderer, then type must always be specified for autocasting to work properly.

Async data

This section covers JavaScript Promises and the Loading pattern in the ArcGIS Maps SDK for JavaScript.

Promises

Promises play an important role in the ArcGIS Maps SDK for JavaScript. Using promises allows for writing cleaner code when working with asynchronous operations.

What is a Promise?

On the most basic level, a promise is a representation of a future value returned from an asynchronous task. When the task executes, the promise allows other processes to run simultaneously while it waits for a future value to be returned. This is particularly useful when making multiple network requests where timing and download speeds can be unpredictable.

A promise is always in one of three states:

  • pending
  • fulfilled
  • rejected

When a promise resolves, it can resolve to a value or another promise as defined in a callback function. When a promise is rejected, it should be handled in an errCallback function.

Using Promises

Promises are commonly used with then(). This is a powerful method that defines the callback function that is called if the promise is resolved, and an error function that is called if the promise is rejected. The first parameter is always the success callback and the second, optional parameter, is the error callback.

Use dark colors for code blocksCopy
1
someAsyncFunction().then(callback, errorCallback);

The callback is invoked once the promise resolves and the errCallback is called if the promise is rejected.

Use dark colors for code blocksCopy
1
2
3
4
5
6
someAsyncFunction()
  .then((resolvedVal) => {
    console.log(resolvedVal);
  }, (error) => {
    console.error(error);
  });

The catch() method can also be used to specify the error callback function for a promise.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
someAsyncFunction()
  .then((resolvedVal) => {
    console.log(resolvedVal);
  })
  .catch((error) => {
    console.error(error);
  });

See Esri Error for more information on error handling.

Example: GeometryService

In this example, the geometryService is used to project several point geometries to a new spatial reference. In the documentation for geometryService.project, notice that project() returns a promise that resolves to an array of projected geometries.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
require([
  "esri/rest/geometryService",
  "esri/rest/support/ProjectParameters",
  ], (geometryService, ProjectParameters) => {

    const geoService = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Utilities/Geometry/GeometryServer";

    const projectParams = new ProjectParameters({
      geometries: [points],   // assuming these are defined elsewhere
      outSR: outSR,
      transformation = transformation
    });

    geometryService.project(geoService, projectParams)
      .then((projectedGeoms) => {
       console.log("projected points: ", projectedGeoms);
      }, (error) => {
        console.error(error);
      });
});

Using async/await

One advantage of promises is they can be used within an async, or asynchronous, function that allows expressions to run synchronously without blocking the execution of other code. This can be accomplished by placing the async keyword before a function definition, and then setting the await keyword on an expression that returns a promise. Code outside of the async function can run in parallel until the promise in the await expression is fulfilled or rejected.

Here is an example using reactiveUtils.once(). This expression waits for the first time the zoom level is greater than 20. Then it returns a promise. After the promise is resolved, a message is written to the console:

Use dark colors for code blocksCopy
1
2
3
4
5
6
  const checkZoomLevel = async () => {
    await reactiveUtils.once(() => view.zoom > 20);
    console.log("Zoom level is greater than 20!");
  }

  checkZoomLevel();

Async functions can contain zero or more await expressions that run sequentially as each promise is resolved. In this example, the compileStastics() function runs simultaneously with the queryPopulation() function. The compileStatistics() function runs view.whenLayerView() and waits for the promise to resolve that indicates the LayerView has been created on the View. Then it uses reactiveUtils.whenOnce() to evaluate when the layer view has finished updating. When that expression evaluates the updating property to be true, the code execution continues to the third expression that calculates statistics, and then the function returns the results.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  // Async function
  const compileStatistics = async () => {
    const layerView = await view.whenLayerView(layer); // assume layer is defined elsewhere
    await reactiveUtils.whenOnce(() => !layerView.updating);
    return await runStats();
  }

  // Async function fulfills or rejects a promise
  compileStastics().then((stats) => {
    console.log(stats);
  })
  .catch((error) => {
    console.error(error);
  });

  // This function runs in parallel
  queryPopulation();

Additional resources

Read more about promises in the MDN Promise documentation as well as async and await to get a more in-depth look at their structure and usage.

The following are additional links to blogs that explain promises with other helpful examples:

Loadable

Resources such as layers, maps, and portal items frequently rely on remote services or datasets on disk to initialize their state. Accessing such data requires the resources to initialize their state asynchronously. The loadable design pattern unifies this behavior, and resources that adopt this pattern are referred to as "loadable."

Loadable resources handle concurrent and repeated requests to allow sharing the same resource instance among various parts of an application. This pattern permits the cancellation of loading a resource for scenarios such as when the service is slow to respond. Finally, loadable resources provide information about their initialization status through explicit states that can be inspected and monitored.

Load status

The loadStatus property on loadable classes returns the state of the loadable resource. Four states are possible.

StateDescription
not-loadedThe resource has not been asked to load its metadata and its state isn't properly initialized.
loadingThe resource is in the process of loading its metadata asynchronously
failedThe resource failed to load its metadata, and the error encountered is available from the loadError property.
loadedThe resource successfully loaded its metadata and its state is properly initialized.

The following state transitions represent the stages that a loadable resource goes through.

loadable-pattern

The Loadable interface includes listeners that make it easy to monitor the status of loadable resources, display progress, and take action when the state changes.

Loading

A resource commences loading its metadata asynchronously when load() is invoked.

At that time, the load status changes from not-loaded to loading. When the asynchronous operation completes, the callback is called. If the operation encounters an error, the error argument in the callback is populated, and loadStatus is set to failed. If the operation completes successfully, the error argument is null and the load status is set to loaded, which means the resource has finished loading its metadata and is now properly initialized.

Many times, the same resource instance is shared by different parts of the application. For example, a legend component and LayerList may have access to the same layer, and they both may want to access the layer's properties to populate their UI. Or the same portal instance may be shared across the application to display the user's items and groups in different parts of the application. load() supports multiple "listeners" to simplify this type of application development. It can be called concurrently and repeatedly, but only one attempt is made to load the metadata. If a load operation is already in progress (loading state) when load() is called, it simply piggy-backs on the outstanding operation and the callback is queued to be invoked when that operation completes.

If the operation has already completed (loaded or failed state) when load() is called, the callback is immediately invoked with the passed result of the operation, be it success or failure, and the state remains unchanged. This makes it safe to liberally call load() on a loadable resource without having to check whether the resource is loaded and without worrying that it will make unnecessary network requests every time.

If a resource has failed to load, calling load() will not change its state. The callback will be invoked immediately with the past load error.

Cancel loading

A resource cancels any outstanding asynchronous operation to load its metadata when cancelLoad() is invoked. This transitions the state from loading to failed. The loadError property will return information that reflects the operation was cancelled.

This method should be used carefully because all enqueued callbacks for that resource instance will get invoked with an error stating that the operation was cancelled. Thus, one component in the application can cancel the load initiated by other components when sharing the same resource instance.

The cancelLoad() method does nothing if the resource is not in the loading state.

Cascading load dependencies

It is common for a loadable resource to depend on loading other loadable resources to properly initialize its state. For example, a portal item cannot finish loading until its parent portal finishes loading. A feature layer cannot be loaded until its associated feature service is first loaded. This situation is referred to as a load dependency.

Loadable operations invoked on any resource transparently cascade through its dependency graph. This helps simplify using loadable resources and puts the responsibility on the resource to correctly establish and manage its load dependencies.

The following code example shows how this cascading behavior leads to concise code. Loading the map causes the portal item to begin loading, which in turn initiates loading its portal. It is unnecessary to load resources explicitly.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const view = new MapView({
  container: "viewDiv"
});

const portal = new Portal({
  url: "https://myportal/"
});

const webmap = new WebMap({
  portalItem: {
    portal: portal,
    id: "f2e9b762544945f390ca4ac3671cfa72"
  }
});

webmap.load()
  .then(() => { view.map = webmap; })
  .catch((error) => {
    console.error("The resource failed to load: ", error);
  });

It is possible that dependencies may fail to load. Some dependencies might be critical, such as a portal item's dependency on its portal. If a failure is encountered while loading such a dependency, that error would bubble up to the resource that initiated the load cycle, which would also fail to load. Other load dependencies may be incidental, such as a map's dependency on one of its operational layers, and the resource may be able to load successfully even if one of its dependency fails to load.

Using when()

The when() method can be used with any loadable class to determine when the class has loaded. This method differs from load() since it does not invoke the loading of a resource. Instead, it should be used with classes that are loaded automatically, like MapView or SceneView.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
const view = new MapView({
  map: map
});

view.when(() => {
  // do something when the view finishes loading
  view.goTo([-112, 38]);
}, (error) => {
  // console an error if the view does not load successfully
  console.log("error loading the view: ", error.message)
});

Using fromJSON

Many classes, including all symbols, geometries, Camera, Viewpoint, Color, and FeatureSet, contain a method called fromJSON().

This function creates an instance of the given class from JSON generated by an ArcGIS product. JSON in this format is typically created from a toJSON() method or a query via the REST API. See the ArcGIS REST API documentation for information and examples of how geometries, symbols, webmaps, etc. are queried and represented in JSON.

The following sample shows how to create a SimpleMarkerSymbol with JSON that was previously retrieved from a query using the REST API.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
require(["esri/symbols/SimpleMarkerSymbol"], (SimpleMarkerSymbol) => {
  // SimpleMarkerSymbol as a JSON response generated from ArcGIS REST API query
  const smsJson = {
    "type": "esriSMS",
    "style": "esriSMSSquare",
    "color": [ 76,115,0,255 ],
    "size": 8,
    "angle": 0,
    "xoffset": 0,
    "yoffset": 0,
    "outline":
    {
      "color": [ 152,230,0,255 ],
      "width": 1
    }
  };

  // Create a SimpleMarkerSymbol from the JSON representation
  const sms = SimpleMarkerSymbol.fromJSON(smsJson);
});

The JSON object passed as the input parameter to fromJSON() may look similar to the object passed as a constructor parameter in the same class. However, these two objects are different in various ways and should not be interchanged. This is because the values and default units of measurement differ between the REST API and the ArcGIS Maps SDK for JavaScript (e.g. symbol size is measured in points with the REST API whereas the ArcGIS Maps SDK for JavaScript uses pixels).

The parameter passed in class constructors is a simple JSON object. This pattern should always be used to create a new instance of a class, unless dealing with JSON previously generated elsewhere from toJSON() or a query to the REST API. Always work with fromJSON(), not the constructor, when creating a class instance from a JSON object in cases where the JSON was previously generated using the REST API or another ArcGIS product (e.g. ArcGIS Server, ArcGIS Online, Portal for ArcGIS, etc.).

Using jsonUtils

There are several jsonUtils classes that are provided as convenience classes when using fromJSON() to instantiate an object, but the type of the object is unknown.

These classes are available for scenarios when a JSON object represents either a geometry, renderer, or symbol from the REST API, but the the object type is unknown. For example, when the renderer of a layer if taken from a REST request and there is uncertainty about whether the renderer is a UniqueValueRenderer, require() the esri/renderers/support/jsonUtils class to help determine the type of the renderer.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
require([ "esri/renderers/support/jsonUtils",
          "esri/layers/FeatureLayer"
], ( rendererJsonUtils, FeatureLayer ) => {

  const rendererJSON = {               // renderer object obtained via REST request
     "authoringInfo":null,
     "type":"uniqueValue",
     "field1":"CLASS",
     "field2":null,
     "field3":null,
     "expression":null,
     "fieldDelimiter":null,
     "defaultSymbol":{
        "color":[
           235,
           235,
           235,
           255
        ],
        "type":"esriSLS",
        "width":3,
        "style":"esriSLSShortDot"
     },
     "defaultLabel":"Other major roads",
     "uniqueValueInfos":[
        {
           "value":"I",
           "symbol":{
              "color":[
                 255,
                 170,
                 0,
                 255
              ],
              "type":"esriSLS",
              "width":10,
              "style":"esriSLSSolid"
           },
           "label":"Interstate"
        },
        {
           "value":"U",
           "symbol":{
              "color":[
                 223,
                 115,
                 255,
                 255
              ],
              "type":"esriSLS",
              "width":7,
              "style":"esriSLSSolid"
           },
           "label":"US Highway"
        }
     ]
  };

  // Create a renderer object from its JSON representation
  const flRenderer = rendererJsonUtils.fromJSON(rendererJSON);

  // Set the renderer on a layer
  const layer = new FeatureLayer({
    renderer: flRenderer
  });
});

Widget viewModel pattern

Additional functionality can be implemented using the viewModel for many of the out-of-the-box widgets.

There are two parts to working with widgets: the widget, and the widget's viewModel. The widget (i.e. view) part is responsible for handling the User Interface (UI) of the widget, meaning how the widget displays and handles user interaction via the DOM, for example the Sketch widget. The viewModel part is responsible for the underlying functionality of the widget, or rather, its business logic, for example SketchViewModel.

Why divide the widget framework into these two separate parts? One reason is reusability. The viewModel exposes the API properties and methods needed for functionality required to support the view, whereas the view contains the DOM logic. Since viewModels extend from esri/core/Accessor, they take advantage of all Accessor's capabilities. This helps keeps consistency between various parts of the API since many other modules derive from this class as well.

So how do these two parts work together? When a widget renders, it renders its state. This state is derived from both view and viewModel properties. At some point within the widget's lifecycle, the view calls upon the viewModel's methods/properties which causes a change to a property or result. After a change is triggered, the view is then notified and will update on the UI.

Here is an example using the SketchViewModel.polygonSymbol property to override the default drawing symbology while actively creating a new graphic:

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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,
});

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