Find a route and directions

Learn how to find a route and directions with the route service.

Routing is the process of finding the path from an origin to a destination in a street network. You can use the route service to find routes, get driving directions, calculate drive times, and solve complicated, multiple vehicle routing problems. To create a route, you typically define a set of stops (origin and one or more destinations) and use the service to find a route with directions. You can also use a number of additional parameters such as barriers and mode of travel to refine the results.

In this tutorial, you use ArcGIS REST JS to access the routing service to get route. You click on the map to get an origin and destination that are used to get a route and directions from the route service. The directions are also displayed on the map.

Prerequisites

You need a free ArcGIS developer account to access your dashboard and API keys. The API key must be scoped to access the services used in this tutorial.

Steps

Create a new pen

  1. To get started, either complete the Display a map tutorial or .

Set the API key

To access ArcGIS location services, you need an API key.

  1. Go to your dashboard to get an API key.

  2. In CodePen, update apiKey to use your key.

    Change line
              
    //
    
    const apiKey = "YOUR-API-KEY";
    const basemapEnum = "ArcGIS:Streets";
    const map = new mapboxgl.Map({
      container: "map", // the id of the div element
      style: `https://basemaps-api.arcgis.com/arcgis/rest/services/styles/${basemapEnum}?type=style&apiKey=${apiKey}`,
      zoom: 12, // starting zoom
      center: [-118.805, 34.027] // starting location [longitude, latitude]
    });
    

Add references to ArcGIS REST JS

  1. In the <head> element, add references to the ArcGIS REST JS library.
Add line.Add line.Add line.
                                                                                                                                                                                                           
<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
    <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
    <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />

    <script src="https://unpkg.com/@esri/arcgis-rest-request@3.0.0/dist/umd/request.umd.js"></script>
    <script src="https://unpkg.com/@esri/arcgis-rest-routing@3.0.0/dist/umd/routing.umd.js"></script>
    <script src="https://unpkg.com/@esri/arcgis-rest-auth@3.0.0/dist/umd/auth.umd.js"></script>


    <style>
      html,
      body,
      #map {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
        font-family: Arial, Helvetica, sans-serif;
        font-size: 14px;
        color: #323232;
      }

      #directions {
        position: absolute;
        width: 30%;
        max-height: 50%;
        right: 20px;
        top: 20px;
        overflow-y: auto; /* Show a scrollbar if needed */
        background: white;
        font-family: Arial, Helvetica, Verdana;
        line-height: 1.5;
        font-size: 14px;
        padding: 10px;
      }

    </style>

  </head>

  <body>
    <div id="map"></div>

    <div id="directions">Click on the map to create a start and end for the route.</div>


    <script>

      const apiKey = "YOUR-API-KEY";

      const basemapEnum = "ArcGIS:Navigation";

      const map = new mapboxgl.Map({
        container: "map", // the id of the div element
        style: `https://basemaps-api.arcgis.com/arcgis/rest/services/styles/${basemapEnum}?type=style&apiKey=${apiKey}`,
        zoom: 12, // starting zoom

        center: [-79.3832,43.6532] // Toronto

      });

      function addCircleLayers() {

        map.addSource("start", {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: []
          }
        });
        map.addSource("end", {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: []
          }
        });

        map.addLayer({
          id: "start-circle",
          type: "circle",
          source: "start",
          paint: {
            "circle-radius": 6,
            "circle-color": "white",
            "circle-stroke-color": "black",
            "circle-stroke-width": 2
          }
        });

        map.addLayer({
          id: "end-circle",
          type: "circle",
          source: "end",
          paint: {
            "circle-radius": 7,
            "circle-color": "black"
          }
        });

      }

      function addRouteLayer() {

        map.addSource("route", {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: []
          }
        });

        map.addLayer({
          id: "route-line",
          type: "line",
          source: "route",

          paint: {
            "line-color": "hsl(205, 100%, 50%)",
            "line-width": 4,
            "line-opacity": 0.6
          }
        });

      }

      function updateRoute() {

        const authentication = new arcgisRest.ApiKey({
          key: apiKey
        });

        arcgisRest
          .solveRoute({
            stops: [startCoords, endCoords],
            endpoint: "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve",
            authentication
          })

          .then((response) => {
            map.getSource("route").setData(response.routes.geoJson);

            const directionsHTML = response.directions[0].features.map((f) => f.attributes.text).join("<br/>");
            document.getElementById("directions").innerHTML = directionsHTML;

          })

          .catch((error) => {
            console.error(error);
            alert("There was a problem using the route service. See the console for details.");
          });

      }

      map.on("load", () => {
        addCircleLayers();

        addRouteLayer();

      });

      let currentStep = "start";
      let startCoords, endCoords;

      map.on("click", (e) => {

        const coordinates = e.lngLat.toArray();
        const point = {
          type: "Point",
          coordinates
        };

        if (currentStep === "start") {
          map.getSource("start").setData(point);
          startCoords = coordinates;
          const empty = {
            type: 'FeatureCollection',
            features: []
          };
          map.getSource("end").setData(empty);
          map.getSource("route").setData(empty)
          endCoords = null;
          currentStep = "end";
        } else {
          map.getSource("end").setData(point);
          endCoords = coordinates;
          currentStep = "start";
        }

        if (startCoords && endCoords) {
          updateRoute(startCoords, endCoords);
        }

      });

    </script>
  </body>
</html>

Update the map

A navigation basemap layer is typically used in geocoding and routing applications. Update the basemap layer to use ArcGIS:Navigation.

  1. Update the basemap and the map initialization to center on location [-79.3832,43.6532], Toronto.

    Change lineChange line
                                                                                                                                                                                                               
    <!DOCTYPE html>
    <html>
    
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
        <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
        <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
    
        <script src="https://unpkg.com/@esri/arcgis-rest-request@3.0.0/dist/umd/request.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-routing@3.0.0/dist/umd/routing.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-auth@3.0.0/dist/umd/auth.umd.js"></script>
    
    
        <style>
          html,
          body,
          #map {
            padding: 0;
            margin: 0;
            height: 100%;
            width: 100%;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #323232;
          }
    
          #directions {
            position: absolute;
            width: 30%;
            max-height: 50%;
            right: 20px;
            top: 20px;
            overflow-y: auto; /* Show a scrollbar if needed */
            background: white;
            font-family: Arial, Helvetica, Verdana;
            line-height: 1.5;
            font-size: 14px;
            padding: 10px;
          }
    
        </style>
    
      </head>
    
      <body>
        <div id="map"></div>
    
        <div id="directions">Click on the map to create a start and end for the route.</div>
    
    
        <script>
    
          const apiKey = "YOUR-API-KEY";
    
          const basemapEnum = "ArcGIS:Navigation";
    
          const map = new mapboxgl.Map({
            container: "map", // the id of the div element
            style: `https://basemaps-api.arcgis.com/arcgis/rest/services/styles/${basemapEnum}?type=style&apiKey=${apiKey}`,
            zoom: 12, // starting zoom
    
            center: [-79.3832,43.6532] // Toronto
    
          });
    
          function addCircleLayers() {
    
            map.addSource("start", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
            map.addSource("end", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "start-circle",
              type: "circle",
              source: "start",
              paint: {
                "circle-radius": 6,
                "circle-color": "white",
                "circle-stroke-color": "black",
                "circle-stroke-width": 2
              }
            });
    
            map.addLayer({
              id: "end-circle",
              type: "circle",
              source: "end",
              paint: {
                "circle-radius": 7,
                "circle-color": "black"
              }
            });
    
          }
    
          function addRouteLayer() {
    
            map.addSource("route", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "route-line",
              type: "line",
              source: "route",
    
              paint: {
                "line-color": "hsl(205, 100%, 50%)",
                "line-width": 4,
                "line-opacity": 0.6
              }
            });
    
          }
    
          function updateRoute() {
    
            const authentication = new arcgisRest.ApiKey({
              key: apiKey
            });
    
            arcgisRest
              .solveRoute({
                stops: [startCoords, endCoords],
                endpoint: "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve",
                authentication
              })
    
              .then((response) => {
                map.getSource("route").setData(response.routes.geoJson);
    
                const directionsHTML = response.directions[0].features.map((f) => f.attributes.text).join("<br/>");
                document.getElementById("directions").innerHTML = directionsHTML;
    
              })
    
              .catch((error) => {
                console.error(error);
                alert("There was a problem using the route service. See the console for details.");
              });
    
          }
    
          map.on("load", () => {
            addCircleLayers();
    
            addRouteLayer();
    
          });
    
          let currentStep = "start";
          let startCoords, endCoords;
    
          map.on("click", (e) => {
    
            const coordinates = e.lngLat.toArray();
            const point = {
              type: "Point",
              coordinates
            };
    
            if (currentStep === "start") {
              map.getSource("start").setData(point);
              startCoords = coordinates;
              const empty = {
                type: 'FeatureCollection',
                features: []
              };
              map.getSource("end").setData(empty);
              map.getSource("route").setData(empty)
              endCoords = null;
              currentStep = "end";
            } else {
              map.getSource("end").setData(point);
              endCoords = coordinates;
              currentStep = "start";
            }
    
            if (startCoords && endCoords) {
              updateRoute(startCoords, endCoords);
            }
    
          });
    
        </script>
      </body>
    </html>

Add end point layers

To display circles for the start and end of the route, you will two circle layers. Each layer needs a GeoJSON source which holds the data.

  1. Create a function called addCircleLayers.

    Add line.Add line.Add line.
                                                                                                                                                                                                               
    <!DOCTYPE html>
    <html>
    
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
        <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
        <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
    
        <script src="https://unpkg.com/@esri/arcgis-rest-request@3.0.0/dist/umd/request.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-routing@3.0.0/dist/umd/routing.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-auth@3.0.0/dist/umd/auth.umd.js"></script>
    
    
        <style>
          html,
          body,
          #map {
            padding: 0;
            margin: 0;
            height: 100%;
            width: 100%;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #323232;
          }
    
          #directions {
            position: absolute;
            width: 30%;
            max-height: 50%;
            right: 20px;
            top: 20px;
            overflow-y: auto; /* Show a scrollbar if needed */
            background: white;
            font-family: Arial, Helvetica, Verdana;
            line-height: 1.5;
            font-size: 14px;
            padding: 10px;
          }
    
        </style>
    
      </head>
    
      <body>
        <div id="map"></div>
    
        <div id="directions">Click on the map to create a start and end for the route.</div>
    
    
        <script>
    
          const apiKey = "YOUR-API-KEY";
    
          const basemapEnum = "ArcGIS:Navigation";
    
          const map = new mapboxgl.Map({
            container: "map", // the id of the div element
            style: `https://basemaps-api.arcgis.com/arcgis/rest/services/styles/${basemapEnum}?type=style&apiKey=${apiKey}`,
            zoom: 12, // starting zoom
    
            center: [-79.3832,43.6532] // Toronto
    
          });
    
          function addCircleLayers() {
    
            map.addSource("start", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
            map.addSource("end", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "start-circle",
              type: "circle",
              source: "start",
              paint: {
                "circle-radius": 6,
                "circle-color": "white",
                "circle-stroke-color": "black",
                "circle-stroke-width": 2
              }
            });
    
            map.addLayer({
              id: "end-circle",
              type: "circle",
              source: "end",
              paint: {
                "circle-radius": 7,
                "circle-color": "black"
              }
            });
    
          }
    
          function addRouteLayer() {
    
            map.addSource("route", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "route-line",
              type: "line",
              source: "route",
    
              paint: {
                "line-color": "hsl(205, 100%, 50%)",
                "line-width": 4,
                "line-opacity": 0.6
              }
            });
    
          }
    
          function updateRoute() {
    
            const authentication = new arcgisRest.ApiKey({
              key: apiKey
            });
    
            arcgisRest
              .solveRoute({
                stops: [startCoords, endCoords],
                endpoint: "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve",
                authentication
              })
    
              .then((response) => {
                map.getSource("route").setData(response.routes.geoJson);
    
                const directionsHTML = response.directions[0].features.map((f) => f.attributes.text).join("<br/>");
                document.getElementById("directions").innerHTML = directionsHTML;
    
              })
    
              .catch((error) => {
                console.error(error);
                alert("There was a problem using the route service. See the console for details.");
              });
    
          }
    
          map.on("load", () => {
            addCircleLayers();
    
            addRouteLayer();
    
          });
    
          let currentStep = "start";
          let startCoords, endCoords;
    
          map.on("click", (e) => {
    
            const coordinates = e.lngLat.toArray();
            const point = {
              type: "Point",
              coordinates
            };
    
            if (currentStep === "start") {
              map.getSource("start").setData(point);
              startCoords = coordinates;
              const empty = {
                type: 'FeatureCollection',
                features: []
              };
              map.getSource("end").setData(empty);
              map.getSource("route").setData(empty)
              endCoords = null;
              currentStep = "end";
            } else {
              map.getSource("end").setData(point);
              endCoords = coordinates;
              currentStep = "start";
            }
    
            if (startCoords && endCoords) {
              updateRoute(startCoords, endCoords);
            }
    
          });
    
        </script>
      </body>
    </html>
  2. Add a GeoJSON source for the start and end, with ids route-start and route-end. Set the data attribute of each source to be an empty FeatureCollection.

    This source will later contain the geometry information of the start or end point that the user has selected. For now, you can simply provide it with an empty piece of GeoJSON: a feature collection that contains no features.

    Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.
                                                                                                                                                                                                               
    <!DOCTYPE html>
    <html>
    
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
        <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
        <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
    
        <script src="https://unpkg.com/@esri/arcgis-rest-request@3.0.0/dist/umd/request.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-routing@3.0.0/dist/umd/routing.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-auth@3.0.0/dist/umd/auth.umd.js"></script>
    
    
        <style>
          html,
          body,
          #map {
            padding: 0;
            margin: 0;
            height: 100%;
            width: 100%;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #323232;
          }
    
          #directions {
            position: absolute;
            width: 30%;
            max-height: 50%;
            right: 20px;
            top: 20px;
            overflow-y: auto; /* Show a scrollbar if needed */
            background: white;
            font-family: Arial, Helvetica, Verdana;
            line-height: 1.5;
            font-size: 14px;
            padding: 10px;
          }
    
        </style>
    
      </head>
    
      <body>
        <div id="map"></div>
    
        <div id="directions">Click on the map to create a start and end for the route.</div>
    
    
        <script>
    
          const apiKey = "YOUR-API-KEY";
    
          const basemapEnum = "ArcGIS:Navigation";
    
          const map = new mapboxgl.Map({
            container: "map", // the id of the div element
            style: `https://basemaps-api.arcgis.com/arcgis/rest/services/styles/${basemapEnum}?type=style&apiKey=${apiKey}`,
            zoom: 12, // starting zoom
    
            center: [-79.3832,43.6532] // Toronto
    
          });
    
          function addCircleLayers() {
    
            map.addSource("start", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
            map.addSource("end", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "start-circle",
              type: "circle",
              source: "start",
              paint: {
                "circle-radius": 6,
                "circle-color": "white",
                "circle-stroke-color": "black",
                "circle-stroke-width": 2
              }
            });
    
            map.addLayer({
              id: "end-circle",
              type: "circle",
              source: "end",
              paint: {
                "circle-radius": 7,
                "circle-color": "black"
              }
            });
    
          }
    
          function addRouteLayer() {
    
            map.addSource("route", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "route-line",
              type: "line",
              source: "route",
    
              paint: {
                "line-color": "hsl(205, 100%, 50%)",
                "line-width": 4,
                "line-opacity": 0.6
              }
            });
    
          }
    
          function updateRoute() {
    
            const authentication = new arcgisRest.ApiKey({
              key: apiKey
            });
    
            arcgisRest
              .solveRoute({
                stops: [startCoords, endCoords],
                endpoint: "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve",
                authentication
              })
    
              .then((response) => {
                map.getSource("route").setData(response.routes.geoJson);
    
                const directionsHTML = response.directions[0].features.map((f) => f.attributes.text).join("<br/>");
                document.getElementById("directions").innerHTML = directionsHTML;
    
              })
    
              .catch((error) => {
                console.error(error);
                alert("There was a problem using the route service. See the console for details.");
              });
    
          }
    
          map.on("load", () => {
            addCircleLayers();
    
            addRouteLayer();
    
          });
    
          let currentStep = "start";
          let startCoords, endCoords;
    
          map.on("click", (e) => {
    
            const coordinates = e.lngLat.toArray();
            const point = {
              type: "Point",
              coordinates
            };
    
            if (currentStep === "start") {
              map.getSource("start").setData(point);
              startCoords = coordinates;
              const empty = {
                type: 'FeatureCollection',
                features: []
              };
              map.getSource("end").setData(empty);
              map.getSource("route").setData(empty)
              endCoords = null;
              currentStep = "end";
            } else {
              map.getSource("end").setData(point);
              endCoords = coordinates;
              currentStep = "start";
            }
    
            if (startCoords && endCoords) {
              updateRoute(startCoords, endCoords);
            }
    
          });
    
        </script>
      </body>
    </html>
  1. Add a layer of type circle for the start and end, connected to those sources. Use the circle-color paint property to make the start circle white and the end circle black.

    Each layer will display the data in its source. Since there is no data in those sources for now, nothing will display yet.
    Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.
                                                                                                                                                                                                               
    <!DOCTYPE html>
    <html>
    
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
        <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
        <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
    
        <script src="https://unpkg.com/@esri/arcgis-rest-request@3.0.0/dist/umd/request.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-routing@3.0.0/dist/umd/routing.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-auth@3.0.0/dist/umd/auth.umd.js"></script>
    
    
        <style>
          html,
          body,
          #map {
            padding: 0;
            margin: 0;
            height: 100%;
            width: 100%;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #323232;
          }
    
          #directions {
            position: absolute;
            width: 30%;
            max-height: 50%;
            right: 20px;
            top: 20px;
            overflow-y: auto; /* Show a scrollbar if needed */
            background: white;
            font-family: Arial, Helvetica, Verdana;
            line-height: 1.5;
            font-size: 14px;
            padding: 10px;
          }
    
        </style>
    
      </head>
    
      <body>
        <div id="map"></div>
    
        <div id="directions">Click on the map to create a start and end for the route.</div>
    
    
        <script>
    
          const apiKey = "YOUR-API-KEY";
    
          const basemapEnum = "ArcGIS:Navigation";
    
          const map = new mapboxgl.Map({
            container: "map", // the id of the div element
            style: `https://basemaps-api.arcgis.com/arcgis/rest/services/styles/${basemapEnum}?type=style&apiKey=${apiKey}`,
            zoom: 12, // starting zoom
    
            center: [-79.3832,43.6532] // Toronto
    
          });
    
          function addCircleLayers() {
    
            map.addSource("start", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
            map.addSource("end", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "start-circle",
              type: "circle",
              source: "start",
              paint: {
                "circle-radius": 6,
                "circle-color": "white",
                "circle-stroke-color": "black",
                "circle-stroke-width": 2
              }
            });
    
            map.addLayer({
              id: "end-circle",
              type: "circle",
              source: "end",
              paint: {
                "circle-radius": 7,
                "circle-color": "black"
              }
            });
    
          }
    
          function addRouteLayer() {
    
            map.addSource("route", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "route-line",
              type: "line",
              source: "route",
    
              paint: {
                "line-color": "hsl(205, 100%, 50%)",
                "line-width": 4,
                "line-opacity": 0.6
              }
            });
    
          }
    
          function updateRoute() {
    
            const authentication = new arcgisRest.ApiKey({
              key: apiKey
            });
    
            arcgisRest
              .solveRoute({
                stops: [startCoords, endCoords],
                endpoint: "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve",
                authentication
              })
    
              .then((response) => {
                map.getSource("route").setData(response.routes.geoJson);
    
                const directionsHTML = response.directions[0].features.map((f) => f.attributes.text).join("<br/>");
                document.getElementById("directions").innerHTML = directionsHTML;
    
              })
    
              .catch((error) => {
                console.error(error);
                alert("There was a problem using the route service. See the console for details.");
              });
    
          }
    
          map.on("load", () => {
            addCircleLayers();
    
            addRouteLayer();
    
          });
    
          let currentStep = "start";
          let startCoords, endCoords;
    
          map.on("click", (e) => {
    
            const coordinates = e.lngLat.toArray();
            const point = {
              type: "Point",
              coordinates
            };
    
            if (currentStep === "start") {
              map.getSource("start").setData(point);
              startCoords = coordinates;
              const empty = {
                type: 'FeatureCollection',
                features: []
              };
              map.getSource("end").setData(empty);
              map.getSource("route").setData(empty)
              endCoords = null;
              currentStep = "end";
            } else {
              map.getSource("end").setData(point);
              endCoords = coordinates;
              currentStep = "start";
            }
    
            if (startCoords && endCoords) {
              updateRoute(startCoords, endCoords);
            }
    
          });
    
        </script>
      </body>
    </html>

Add a load event handler

At this stage, the layers have not been added to the map. It is important to wait for the map to finish loading before adding the layers.

  1. Add an event handler to the map load event. Call the addCircleLayers function.

    Add line.Add line.Add line.Add line.Add line.Add line.
                                                                                                                                                                                                               
    <!DOCTYPE html>
    <html>
    
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
        <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
        <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
    
        <script src="https://unpkg.com/@esri/arcgis-rest-request@3.0.0/dist/umd/request.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-routing@3.0.0/dist/umd/routing.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-auth@3.0.0/dist/umd/auth.umd.js"></script>
    
    
        <style>
          html,
          body,
          #map {
            padding: 0;
            margin: 0;
            height: 100%;
            width: 100%;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #323232;
          }
    
          #directions {
            position: absolute;
            width: 30%;
            max-height: 50%;
            right: 20px;
            top: 20px;
            overflow-y: auto; /* Show a scrollbar if needed */
            background: white;
            font-family: Arial, Helvetica, Verdana;
            line-height: 1.5;
            font-size: 14px;
            padding: 10px;
          }
    
        </style>
    
      </head>
    
      <body>
        <div id="map"></div>
    
        <div id="directions">Click on the map to create a start and end for the route.</div>
    
    
        <script>
    
          const apiKey = "YOUR-API-KEY";
    
          const basemapEnum = "ArcGIS:Navigation";
    
          const map = new mapboxgl.Map({
            container: "map", // the id of the div element
            style: `https://basemaps-api.arcgis.com/arcgis/rest/services/styles/${basemapEnum}?type=style&apiKey=${apiKey}`,
            zoom: 12, // starting zoom
    
            center: [-79.3832,43.6532] // Toronto
    
          });
    
          function addCircleLayers() {
    
            map.addSource("start", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
            map.addSource("end", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "start-circle",
              type: "circle",
              source: "start",
              paint: {
                "circle-radius": 6,
                "circle-color": "white",
                "circle-stroke-color": "black",
                "circle-stroke-width": 2
              }
            });
    
            map.addLayer({
              id: "end-circle",
              type: "circle",
              source: "end",
              paint: {
                "circle-radius": 7,
                "circle-color": "black"
              }
            });
    
          }
    
          function addRouteLayer() {
    
            map.addSource("route", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "route-line",
              type: "line",
              source: "route",
    
              paint: {
                "line-color": "hsl(205, 100%, 50%)",
                "line-width": 4,
                "line-opacity": 0.6
              }
            });
    
          }
    
          function updateRoute() {
    
            const authentication = new arcgisRest.ApiKey({
              key: apiKey
            });
    
            arcgisRest
              .solveRoute({
                stops: [startCoords, endCoords],
                endpoint: "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve",
                authentication
              })
    
              .then((response) => {
                map.getSource("route").setData(response.routes.geoJson);
    
                const directionsHTML = response.directions[0].features.map((f) => f.attributes.text).join("<br/>");
                document.getElementById("directions").innerHTML = directionsHTML;
    
              })
    
              .catch((error) => {
                console.error(error);
                alert("There was a problem using the route service. See the console for details.");
              });
    
          }
    
          map.on("load", () => {
            addCircleLayers();
    
            addRouteLayer();
    
          });
    
          let currentStep = "start";
          let startCoords, endCoords;
    
          map.on("click", (e) => {
    
            const coordinates = e.lngLat.toArray();
            const point = {
              type: "Point",
              coordinates
            };
    
            if (currentStep === "start") {
              map.getSource("start").setData(point);
              startCoords = coordinates;
              const empty = {
                type: 'FeatureCollection',
                features: []
              };
              map.getSource("end").setData(empty);
              map.getSource("route").setData(empty)
              endCoords = null;
              currentStep = "end";
            } else {
              map.getSource("end").setData(point);
              endCoords = coordinates;
              currentStep = "start";
            }
    
            if (startCoords && endCoords) {
              updateRoute(startCoords, endCoords);
            }
    
          });
    
        </script>
      </body>
    </html>

Add a click handler

You will click twice to set a start and end for the route. The first click will update the start source. The second click will update the end source. To set the GeoJSON data you use map.getSource to get the Source, then call setData.

You use a click event handler to respond to these clicks.

The object passed to the click event contains several useful properties, including:

  • lngLat: the map location where the click took place.
  • point: the screen location in pixels where the click took place.
  • originalEvent: the DOM event, which contains information about modifier keys.

For more information, see the Mapbox GL JS documentation.

  1. Add a variable to store whether the next click will be for the start or end of the route. Set it initially to start. Add a variable to store the coordinates for each end.

    Add line.Add line.
                                                                                                                                                                                                               
    <!DOCTYPE html>
    <html>
    
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
        <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
        <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
    
        <script src="https://unpkg.com/@esri/arcgis-rest-request@3.0.0/dist/umd/request.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-routing@3.0.0/dist/umd/routing.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-auth@3.0.0/dist/umd/auth.umd.js"></script>
    
    
        <style>
          html,
          body,
          #map {
            padding: 0;
            margin: 0;
            height: 100%;
            width: 100%;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #323232;
          }
    
          #directions {
            position: absolute;
            width: 30%;
            max-height: 50%;
            right: 20px;
            top: 20px;
            overflow-y: auto; /* Show a scrollbar if needed */
            background: white;
            font-family: Arial, Helvetica, Verdana;
            line-height: 1.5;
            font-size: 14px;
            padding: 10px;
          }
    
        </style>
    
      </head>
    
      <body>
        <div id="map"></div>
    
        <div id="directions">Click on the map to create a start and end for the route.</div>
    
    
        <script>
    
          const apiKey = "YOUR-API-KEY";
    
          const basemapEnum = "ArcGIS:Navigation";
    
          const map = new mapboxgl.Map({
            container: "map", // the id of the div element
            style: `https://basemaps-api.arcgis.com/arcgis/rest/services/styles/${basemapEnum}?type=style&apiKey=${apiKey}`,
            zoom: 12, // starting zoom
    
            center: [-79.3832,43.6532] // Toronto
    
          });
    
          function addCircleLayers() {
    
            map.addSource("start", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
            map.addSource("end", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "start-circle",
              type: "circle",
              source: "start",
              paint: {
                "circle-radius": 6,
                "circle-color": "white",
                "circle-stroke-color": "black",
                "circle-stroke-width": 2
              }
            });
    
            map.addLayer({
              id: "end-circle",
              type: "circle",
              source: "end",
              paint: {
                "circle-radius": 7,
                "circle-color": "black"
              }
            });
    
          }
    
          function addRouteLayer() {
    
            map.addSource("route", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "route-line",
              type: "line",
              source: "route",
    
              paint: {
                "line-color": "hsl(205, 100%, 50%)",
                "line-width": 4,
                "line-opacity": 0.6
              }
            });
    
          }
    
          function updateRoute() {
    
            const authentication = new arcgisRest.ApiKey({
              key: apiKey
            });
    
            arcgisRest
              .solveRoute({
                stops: [startCoords, endCoords],
                endpoint: "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve",
                authentication
              })
    
              .then((response) => {
                map.getSource("route").setData(response.routes.geoJson);
    
                const directionsHTML = response.directions[0].features.map((f) => f.attributes.text).join("<br/>");
                document.getElementById("directions").innerHTML = directionsHTML;
    
              })
    
              .catch((error) => {
                console.error(error);
                alert("There was a problem using the route service. See the console for details.");
              });
    
          }
    
          map.on("load", () => {
            addCircleLayers();
    
            addRouteLayer();
    
          });
    
          let currentStep = "start";
          let startCoords, endCoords;
    
          map.on("click", (e) => {
    
            const coordinates = e.lngLat.toArray();
            const point = {
              type: "Point",
              coordinates
            };
    
            if (currentStep === "start") {
              map.getSource("start").setData(point);
              startCoords = coordinates;
              const empty = {
                type: 'FeatureCollection',
                features: []
              };
              map.getSource("end").setData(empty);
              map.getSource("route").setData(empty)
              endCoords = null;
              currentStep = "end";
            } else {
              map.getSource("end").setData(point);
              endCoords = coordinates;
              currentStep = "start";
            }
    
            if (startCoords && endCoords) {
              updateRoute(startCoords, endCoords);
            }
    
          });
    
        </script>
      </body>
    </html>
  2. Add a click event handler to the map. Use the lngLat property of the event parameter to create a GeoJSON Point object.

    Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.
                                                                                                                                                                                                               
    <!DOCTYPE html>
    <html>
    
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
        <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
        <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
    
        <script src="https://unpkg.com/@esri/arcgis-rest-request@3.0.0/dist/umd/request.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-routing@3.0.0/dist/umd/routing.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-auth@3.0.0/dist/umd/auth.umd.js"></script>
    
    
        <style>
          html,
          body,
          #map {
            padding: 0;
            margin: 0;
            height: 100%;
            width: 100%;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #323232;
          }
    
          #directions {
            position: absolute;
            width: 30%;
            max-height: 50%;
            right: 20px;
            top: 20px;
            overflow-y: auto; /* Show a scrollbar if needed */
            background: white;
            font-family: Arial, Helvetica, Verdana;
            line-height: 1.5;
            font-size: 14px;
            padding: 10px;
          }
    
        </style>
    
      </head>
    
      <body>
        <div id="map"></div>
    
        <div id="directions">Click on the map to create a start and end for the route.</div>
    
    
        <script>
    
          const apiKey = "YOUR-API-KEY";
    
          const basemapEnum = "ArcGIS:Navigation";
    
          const map = new mapboxgl.Map({
            container: "map", // the id of the div element
            style: `https://basemaps-api.arcgis.com/arcgis/rest/services/styles/${basemapEnum}?type=style&apiKey=${apiKey}`,
            zoom: 12, // starting zoom
    
            center: [-79.3832,43.6532] // Toronto
    
          });
    
          function addCircleLayers() {
    
            map.addSource("start", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
            map.addSource("end", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "start-circle",
              type: "circle",
              source: "start",
              paint: {
                "circle-radius": 6,
                "circle-color": "white",
                "circle-stroke-color": "black",
                "circle-stroke-width": 2
              }
            });
    
            map.addLayer({
              id: "end-circle",
              type: "circle",
              source: "end",
              paint: {
                "circle-radius": 7,
                "circle-color": "black"
              }
            });
    
          }
    
          function addRouteLayer() {
    
            map.addSource("route", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "route-line",
              type: "line",
              source: "route",
    
              paint: {
                "line-color": "hsl(205, 100%, 50%)",
                "line-width": 4,
                "line-opacity": 0.6
              }
            });
    
          }
    
          function updateRoute() {
    
            const authentication = new arcgisRest.ApiKey({
              key: apiKey
            });
    
            arcgisRest
              .solveRoute({
                stops: [startCoords, endCoords],
                endpoint: "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve",
                authentication
              })
    
              .then((response) => {
                map.getSource("route").setData(response.routes.geoJson);
    
                const directionsHTML = response.directions[0].features.map((f) => f.attributes.text).join("<br/>");
                document.getElementById("directions").innerHTML = directionsHTML;
    
              })
    
              .catch((error) => {
                console.error(error);
                alert("There was a problem using the route service. See the console for details.");
              });
    
          }
    
          map.on("load", () => {
            addCircleLayers();
    
            addRouteLayer();
    
          });
    
          let currentStep = "start";
          let startCoords, endCoords;
    
          map.on("click", (e) => {
    
            const coordinates = e.lngLat.toArray();
            const point = {
              type: "Point",
              coordinates
            };
    
            if (currentStep === "start") {
              map.getSource("start").setData(point);
              startCoords = coordinates;
              const empty = {
                type: 'FeatureCollection',
                features: []
              };
              map.getSource("end").setData(empty);
              map.getSource("route").setData(empty)
              endCoords = null;
              currentStep = "end";
            } else {
              map.getSource("end").setData(point);
              endCoords = coordinates;
              currentStep = "start";
            }
    
            if (startCoords && endCoords) {
              updateRoute(startCoords, endCoords);
            }
    
          });
    
        </script>
      </body>
    </html>
  3. Use map.getSource and the setData method to update the correct source with the GeoJSON object.

    Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.
                                                                                                                                                                                                               
    <!DOCTYPE html>
    <html>
    
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
        <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
        <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
    
        <script src="https://unpkg.com/@esri/arcgis-rest-request@3.0.0/dist/umd/request.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-routing@3.0.0/dist/umd/routing.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-auth@3.0.0/dist/umd/auth.umd.js"></script>
    
    
        <style>
          html,
          body,
          #map {
            padding: 0;
            margin: 0;
            height: 100%;
            width: 100%;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #323232;
          }
    
          #directions {
            position: absolute;
            width: 30%;
            max-height: 50%;
            right: 20px;
            top: 20px;
            overflow-y: auto; /* Show a scrollbar if needed */
            background: white;
            font-family: Arial, Helvetica, Verdana;
            line-height: 1.5;
            font-size: 14px;
            padding: 10px;
          }
    
        </style>
    
      </head>
    
      <body>
        <div id="map"></div>
    
        <div id="directions">Click on the map to create a start and end for the route.</div>
    
    
        <script>
    
          const apiKey = "YOUR-API-KEY";
    
          const basemapEnum = "ArcGIS:Navigation";
    
          const map = new mapboxgl.Map({
            container: "map", // the id of the div element
            style: `https://basemaps-api.arcgis.com/arcgis/rest/services/styles/${basemapEnum}?type=style&apiKey=${apiKey}`,
            zoom: 12, // starting zoom
    
            center: [-79.3832,43.6532] // Toronto
    
          });
    
          function addCircleLayers() {
    
            map.addSource("start", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
            map.addSource("end", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "start-circle",
              type: "circle",
              source: "start",
              paint: {
                "circle-radius": 6,
                "circle-color": "white",
                "circle-stroke-color": "black",
                "circle-stroke-width": 2
              }
            });
    
            map.addLayer({
              id: "end-circle",
              type: "circle",
              source: "end",
              paint: {
                "circle-radius": 7,
                "circle-color": "black"
              }
            });
    
          }
    
          function addRouteLayer() {
    
            map.addSource("route", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "route-line",
              type: "line",
              source: "route",
    
              paint: {
                "line-color": "hsl(205, 100%, 50%)",
                "line-width": 4,
                "line-opacity": 0.6
              }
            });
    
          }
    
          function updateRoute() {
    
            const authentication = new arcgisRest.ApiKey({
              key: apiKey
            });
    
            arcgisRest
              .solveRoute({
                stops: [startCoords, endCoords],
                endpoint: "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve",
                authentication
              })
    
              .then((response) => {
                map.getSource("route").setData(response.routes.geoJson);
    
                const directionsHTML = response.directions[0].features.map((f) => f.attributes.text).join("<br/>");
                document.getElementById("directions").innerHTML = directionsHTML;
    
              })
    
              .catch((error) => {
                console.error(error);
                alert("There was a problem using the route service. See the console for details.");
              });
    
          }
    
          map.on("load", () => {
            addCircleLayers();
    
            addRouteLayer();
    
          });
    
          let currentStep = "start";
          let startCoords, endCoords;
    
          map.on("click", (e) => {
    
            const coordinates = e.lngLat.toArray();
            const point = {
              type: "Point",
              coordinates
            };
    
            if (currentStep === "start") {
              map.getSource("start").setData(point);
              startCoords = coordinates;
              const empty = {
                type: 'FeatureCollection',
                features: []
              };
              map.getSource("end").setData(empty);
              map.getSource("route").setData(empty)
              endCoords = null;
              currentStep = "end";
            } else {
              map.getSource("end").setData(point);
              endCoords = coordinates;
              currentStep = "start";
            }
    
            if (startCoords && endCoords) {
              updateRoute(startCoords, endCoords);
            }
    
          });
    
        </script>
      </body>
    </html>
  4. At the top right, click Run. You should be able to click in two places to set a white circle for the start, and a black circle for the end.

Add route layer

The route object that will be retrieved is a GeoJSON LineString object. To display it, you define a GeoJSON source and a line layer.

  1. Create a addRouteLayer function. Inside, add a source of type geojson with id route. Set its data attribute to be an empty FeatureCollection.

    Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.
                                                                                                                                                                                                               
    <!DOCTYPE html>
    <html>
    
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
        <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
        <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
    
        <script src="https://unpkg.com/@esri/arcgis-rest-request@3.0.0/dist/umd/request.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-routing@3.0.0/dist/umd/routing.umd.js"></script>
        <script src="https://unpkg.com/@esri/arcgis-rest-auth@3.0.0/dist/umd/auth.umd.js"></script>
    
    
        <style>
          html,
          body,
          #map {
            padding: 0;
            margin: 0;
            height: 100%;
            width: 100%;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #323232;
          }
    
          #directions {
            position: absolute;
            width: 30%;
            max-height: 50%;
            right: 20px;
            top: 20px;
            overflow-y: auto; /* Show a scrollbar if needed */
            background: white;
            font-family: Arial, Helvetica, Verdana;
            line-height: 1.5;
            font-size: 14px;
            padding: 10px;
          }
    
        </style>
    
      </head>
    
      <body>
        <div id="map"></div>
    
        <div id="directions">Click on the map to create a start and end for the route.</div>
    
    
        <script>
    
          const apiKey = "YOUR-API-KEY";
    
          const basemapEnum = "ArcGIS:Navigation";
    
          const map = new mapboxgl.Map({
            container: "map", // the id of the div element
            style: `https://basemaps-api.arcgis.com/arcgis/rest/services/styles/${basemapEnum}?type=style&apiKey=${apiKey}`,
            zoom: 12, // starting zoom
    
            center: [-79.3832,43.6532] // Toronto
    
          });
    
          function addCircleLayers() {
    
            map.addSource("start", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
            map.addSource("end", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "start-circle",
              type: "circle",
              source: "start",
              paint: {
                "circle-radius": 6,
                "circle-color": "white",
                "circle-stroke-color": "black",
                "circle-stroke-width": 2
              }
            });
    
            map.addLayer({
              id: "end-circle",
              type: "circle",
              source: "end",
              paint: {
                "circle-radius": 7,
                "circle-color": "black"
              }
            });
    
          }
    
          function addRouteLayer() {
    
            map.addSource("route", {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: []
              }
            });
    
            map.addLayer({
              id: "route-line",
              type: "line",
              source: "route",
    
              paint: {
                "line-color": "hsl(205, 100%, 50%)",
                "line-width": 4,
                "line-opacity": 0.6
              }
            });
    
          }
    
          function updateRoute() {
    
            const authentication = new arcgisRest.ApiKey({
              key: apiKey
            });
    
            arcgisRest
              .solveRoute({
                stops: [startCoords, endCoords],
                endpoint: "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve",
                authentication
              })
    
              .then((response) => {
                map.getSource("route").setData(response.routes.geoJson);
    
                const directionsHTML = response.directions[0].features.map((f) => f.attributes.text).join("<br/>");
                document.getElementById("directions").innerHTML = directionsHTML;
    
              })
    
              .catch((error) => {
                console.error(error);
                alert("There was a problem using the route service. See the console for details.");
              });
    
          }
    
          map.on("load", () => {
            addCircleLayers();
    
            addRouteLayer();
    
          });
    
          let currentStep = "start";
          let startCoords, endCoords;
    
          map.on("click", (e) => {
    
            const coordinates = e.lngLat.toArray();
            const point = {
              type: "Point",
              coordinates
            };
    
            if (currentStep === "start") {
              map.getSource("start").setData(point);
              startCoords = coordinates;
              const empty = {
                type: 'FeatureCollection',
                features: []
              };
              map.getSource("end").setData(empty);
              map.getSource("route").setData(empty)
              endCoords = null;
              currentStep = "end";
            } else {
              map.getSource("end").setData(point);
              endCoords = coordinates;
              currentStep = "start";
            }
    
            if (startCoords && endCoords) {
              updateRoute(startCoords, endCoords);
            }
    
          });
    
        </script>
      </body>
    </html>
  2. Add a layer of type line with id route-line. Set its source to be route, and give it width, color and opacity attributes.

    This source will later contain the geometry information of the route between points that the user has selected. For now, you can simply provide it with an empty piece of GeoJSON: a feature collection that contains no features.

    The layer will display the source. Since there is no data in the source for now, nothing will display yet.

    Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.