Programming patterns

This topic covers common usage patterns and best practices for components and the core API when building applications with the ArcGIS Maps SDK for JavaScript.

Attributes and properties

ArcGIS Maps SDK for JavaScript components' HTML attributes and JavaScript properties, while similar in concept, have some key differences. HTML attributes are always strings and they can be set directly on the HTML element or programmatically in JavaScript. Even when setting what seems like a number, the attribute value is still a string. In HTML, the presence of an boolean attribute means it is true and its absence means it is false, such as drag-enabled in the snippet below. Setting attribute strings to "true" and "false" is invalid. Attributes are written in kebab-case, while properties are in camelCase.

Use dark colors for code blocksCopy
1
2
3
4
5
<body>
  <arcgis-map id="my-map" item-id="05e015c5f0314db9a487a9b46cb37eca"></arcgis-map>
  <arcgis-layer-list reference-element="my-map" drag-enabled selection-mode="multiple">
  </arcgis-layer-list>
</body>

On the other hand, JavaScript properties can be any valid JavaScript data type, including strings, booleans, numbers, arrays, objects, functions, and more. Properties can only be set programmatically using JavaScript. Most properties have an associated attribute, but not all. If a property type does not include a string, number, or boolean, it will not have an associated attribute.

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
// Get a reference to the arcgis-layer-list component
const arcgisLayerList = document.querySelector("arcgis-layer-list");

// Set properties with various data types

// arcgis-map component
arcgisLayerList.referenceElement = document.querySelector("#my-map");
// boolean
arcgisLayerList.dragEnabled = true;
// function
arcgisLayerList.listItemCreatedFunction = (event) => {
  const { item } = event;
  if (item.layer.type != "group") {
    item.panel = {
      content: "legend",
    };
  }
};
// string
arcgisLayerList.selectionMode = "multiple";
// object
arcgisLayerList.visibleElements = {
  ...arcgisLayerList.visibleElements,
  ...{
    statusIndicators: false,
  },
};

Boolean attributes

Boolean attributes present a special case in HTML elements. The presence of the attribute in an HTML tag always indicates a value of true, and absence of the attribute from the tag indicates a value of false. It is invalid to set a boolean attribute using the string values "true" or "false". Here is an example using the Map components popup-disabled attribute:

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
<!-- Best practice: set popup-disabled to true -->
<arcgis-map popup-disabled></arcgis-map>

<!-- Best practice: set popup-disabled to false (default) -->
<arcgis-map></arcgis-map>

<!-- Invalid: don't use strings to set boolean values -->
<arcgis-map popup-disabled="true"></arcgis-map>

More information is available in the Boolean attribute (HTML) MDN article.

HTML start and end tags

Components from the ArcGIS Maps SDK for JavaScript are standards-based custom HTML elements, which means they must have a start and end tag in HTML. They cannot be self-closing in HTML.

Use dark colors for code blocksCopy
1
2
3
4
5
<!-- Best practice: start and end tags -->
<arcgis-map></arcgis-map>

<!-- Invalid HTML: self-closing tags -->
<arcgis-map />

Associate components with a Map or Scene component

The Map and Scene components are parent containers for building interactive 2D and 3D visualization experiences. Other components from the @arcgis/map-components package can be associated with a Map or Scene component to provide additional functionality, such as adding a legend, layer list, search, and more. There are two methods to associate components from @arcgis/map-components package to a Map or Scene component. The first method involves including the component as a child element of the Map or Scene component.

Use dark colors for code blocksCopy
1
2
3
<arcgis-map item-id="05e015c5f0314db9a487a9b46cb37eca">
  <arcgis-legend position="bottom-right"></arcgis-legend>
</arcgis-map>

The second is to use the reference-element attribute on the component. By passing the id of the Map or Scene component into this attribute, you can position components from the @arcgis/map-components package anywhere in the DOM while still maintaining a connection to the Map or Scene.

Use dark colors for code blocksCopy
1
2
<arcgis-map id="my-map" item-id="05e015c5f0314db9a487a9b46cb37eca"></arcgis-map>
<arcgis-legend reference-element="my-map"></arcgis-legend>

Configure Map and Scene components

When using the arcgis-map component, you can initialize it with either a Map or a WebMap. The arcgis-scene component can be initialized with either a Map or WebScene. The choice depends on whether you want to configure the functionality and layers programmatically (e.g. Map) or leverage pre-configured portal items (e.g. WebMap, WebScene).

Using the item-id attribute

The item-id attribute is used to specify the portal item ID of the WebMap or WebScene that you want to load into the arcgis-map or arcgis-scene component. When an item-id is provided to an arcgis-map component, the map property will be initialized with a WebMap instance.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
<body>
  <arcgis-map
    item-id="05e015c5f0314db9a487a9b46cb37eca"
    center="-73.97, 40.77"
    zoom="10"></arcgis-map>
  <script type="module">
    const viewElement = document.querySelector("arcgis-map");
    await viewElement.viewOnReady();
    // Add more functionality here.
  </script>
</body>

Using Map

You can add layers and a basemap programmatically via the Map instance.

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
<body>
  <arcgis-map>
    <arcgis-zoom position="top-left"></arcgis-zoom>
  </arcgis-map>
  <script type="module">
    const [Map, Layer] = await $arcgis.import([
      "@arcgis/core/Map.js",
      "@arcgis/core/layers/Layer.js",
    ]);
    const viewElement = document.querySelector("arcgis-map");

    const layer = await Layer.fromPortalItem({
      portalItem: {
        id: "0566a63fbc6a4dd498072dc4cfbd0616",
      },
    });

    viewElement.map = new Map({
      basemap: "topo-vector",
      layers: [layer],
    });

    viewElement.center = [-73.97, 40.77];
    viewElement.zoom = 10;
  </script>
</body>

Using WebMap (or WebScene)

The WebMap automatically loads the layers and map configuration defined by the portal item ID, making it ideal for quickly adding maps that have been created in Map Viewer. Here is an example:

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
const WebMap = await $arcgis.import("@arcgis/core/WebMap.js");

const viewElement = document.querySelector("arcgis-map");
const webmap = new WebMap({
  portalItem: {
    id: "e691172598f04ea8881cd2a4adaa45ba",
  },
});

// Set a web map on the arcgis-map component's map property
viewElement.map = webmap;

To learn how to create a web map, you can follow this tutorial.

Position custom content on a map or scene component

The arcgis-map and arcgis-scene components can be used as containers for custom content, such as buttons, or other HTML elements. To add custom content, you can use the arcgis-placement component. This component allows you to position custom content on the map or scene using the position attribute.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
<arcgis-map item-id="d5dda743788a4b0688fe48f43ae7beb9">
  <arcgis-placement position="bottom-left">
    <button>Click me</button>
    <arcgis-expand>
      <arcgis-legend></arcgis-legend>
    </arcgis-expand>
  </arcgis-placement>
</arcgis-map>

Component visibility

There are several patterns for toggling the visibility of components. For components that have the showCloseButton property, such as Layer List, the button can be enabled by setting the component's show-close-button attribute, or in JavaScript using the showCloseButton property:

index.html
Use dark colors for code blocksCopy
1
2
<arcgis-layer-list position="top-right" show-close-button>
</arcgis-layer-list>
main.js
Use dark colors for code blocksCopy
1
2
3
4
5
const layerListElement = document.querySelector("arcgis-layer-list");

// Wait for the component to be ready
await layerListElement.componentOnReady();
layerListElement.showCloseButton = true;

For all other components, create your own toggle button and set the auto-destroy-disabled attribute on the component. Then use the Element.remove() method to hide it, and the Element.append() method on the parent element to make the component visible again:

index.html
Use dark colors for code blocksCopy
1
2
3
4
5
<arcgis-time-slider position="bottom-right" auto-destroy-disabled>
</arcgis-time-slider>
<arcgis-placement position="top-left">
  <button id="toggle-button" class="esri-button">Toggle time slider</button>
</arcgis-placement>
main.js
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
let isVisible = true;
const viewElement = document.querySelector("arcgis-map");
const timeSliderElement = document.querySelector("arcgis-time-slider")
document.getElementById("toggle-button").addEventListener("click", ()=>{
  if (isVisible) {
    timeSliderElement.remove();
  } else {
    viewElement.append(timeSliderElement);
  }
  isVisible = !isVisible;
}

Configure global properties

You can use the global esriConfig variable to configure global properties of the JavaScript Maps SDK (API and components), such as the portalUrl.

Set the portalUrl in a CDN application

To configure esriConfig use $arcgis.import() function. Define it inside a <script> tag with type="module" and use top-level await. This ensures esriConfig is set before any components load.

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
<html>
  <head>
    <!-- Load the ArcGIS Maps SDK for JavaScript -->
    <link rel="stylesheet" href="https://js.arcgis.com/4.33/esri/themes/light/main.css" />
    <script src="https://js.arcgis.com/4.33/"></script>

    <script type="module">
      // Import esriConfig and set the portal URL
      const esriConfig = await $arcgis.import("@arcgis/core/config.js");
      esriConfig.portalUrl = "https://myHostName.esri.com/arcgis";
    </script>

    <!-- Load map components -->
    <script type="module" src="https://js.arcgis.com/4.33/map-components/"></script>
  </head>
  <body>
    <arcgis-map item-id="d5dda743788a4b0688fe48f43ae7beb9">
      <arcgis-legend position="bottom-left"></arcgis-legend>
    </arcgis-map>
  </body>
</html>

Set the portalUrl in an ESM application

Importing @arcgis/core/config.js is necessary for configuring the global esriConfig object in ESM applications. Applications hosted on a different portal can be initialized before being passed to the arcgis-map component:

ESM
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
import esriConfig from "@arcgis/core/config.js";
import WebMap from "@arcgis/core/WebMap.js";
import esriId from "@arcgis/core/identity/IdentityManager.js";
import OAuthInfo from "@arcgis/core/identity/OAuthInfo.js";

const portalUrl = "https://myHostName.esri.com/arcgis";
const viewElement = document.querySelector("arcgis-map");

esriConfig.portalUrl = portalUrl;

// Bonus: register OAuth info
esriId.registerOAuthInfos([
  new OAuthInfo({
    appId: "...",
    portalUrl
  });
]);

const webmap = new WebMap({
  portalItem: {
    id: "..."
  }
})

// Pass the webmap to the `arcgis-map` component
viewElement.map = webmap;

Use of multiple portals

If your app uses web maps from different portals (e.g., ArcGIS Online and one or more Enterprise portals), setting a global esriConfig.portalUrl is not sufficient. Instead, create WebMap instances manually and assign the correct portal URL per item.

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
<!-- Application loads maps from two different portals -->

<arcgis-map id="map1"></arcgis-map>
<arcgis-map id="map2"></arcgis-map>

<script type="module">
  import WebMap from "https://js.arcgis.com/4.33/esri/WebMap.js";

  // WebMap from an Enterprise portal
  const webmap1 = new WebMap({
    portalItem: {
      id: "c2275ca6e3f74a3c9fe9ecd66948b1af",
      portal: {
        url: "https://myHostName.esri.com/arcgis"
      }
    }
  });

  // WebMap from ArcGIS Online (default portal)
  const webmap2 = new WebMap({
    portalItem: {
      id: "66bf7d61948b4ef48aea94327b504f86"
    }
  });

  const mapElement1 = document.querySelector("#map1");
  const mapElement2 = document.querySelector("#map2");

  mapElement1.map = webmap1;
  mapElement2.map = webmap2;

  // Listen for view ready changes
  mapElement1.addEventListener("arcgisViewReadyChange", (event) => {
    console.log("map1 view is ready:", event.detail.view);
  });

  mapElement2.addEventListener("arcgisViewReadyChange", (event) => {
    console.log("map2 view is ready:", event.detail.view);
  });
</script>

This pattern ensures each WebMap loads from its appropriate source, making it ideal for environments with a number of different portals.

Using the arcgisViewReadyChange event is recommended here, as it reliably fires each time a map, basemap, or item-id is changed and a new view is created. And if you want to wait until all views are ready before proceeding, use viewOnReady():

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
 // Wait for both views to be ready before proceeding
    async function initialize() {
      const [view1, view2] = await Promise.all([
        mapElement1.viewOnReady(),
        mapElement2.viewOnReady()
      ]);
      console.log("Both views are ready", view1, view2);

      // Example: sync controls or access layer views, etc.
    }

    initialize();

Localization

The language and direction of some web components, such as @arcgis/charts-components and @arcgis/coding-components, can be inherited from the root of the HTML document in the host application, the component itself, or the component's closest parent element. This is a bottom up approach. In cases where a language and direction are not provided, the component will default to left-to-right (ltr) and English (en). See locale support for the full list of supported languages.

Setting the language

Use the ISO language code for setting the language in the lang attribute.

Use dark colors for code blocksCopy
1
<html lang="fr"></html>

Setting the direction

You only need to do this for Arabic and Hebrew.

Use dark colors for code blocksCopy
1
<html dir="rtl" lang="he"></html>

Widget viewModel pattern

Additional functionality can be implemented using the viewModel for many of the widgets. Each widget has a view and a viewModel. The view is generally responsible for handling the User Interface (UI) of the widget, for example the Sketch widget. The viewModel is typically responsible for the business logic, for example SketchViewModel.

The viewModels extend esri/core/Accessor and take advantage of its capabilities. This helps keeps consistency between various parts of the API.

Widget state is derived from both view and viewModel properties. At some point within the widget's lifecycle, the view calls the viewModel's methods and properties. Changes to the viewModel can also trigger the view to update the UI.

Here is a code snippet using the SketchViewModel.polygonSymbol property to override the default drawing symbology:

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.