Learn how to find a route and directions with the ArcGIS Routing service.
Prerequisites
You need an ArcGIS Location Platform or ArcGIS Online account.
Steps
Create a new app
-
Open a terminal and create a new folder for your project.
Use dark colors for code blocks Copy mkdir find-a-route-and-directions cd find-a-route-and-directions -
Initialize a new Node.js project. This creates a
package.jsonfile.Use dark colors for code blocks Copy npm init -
Install the required packages.
Use dark colors for code blocks Copy npm install @esri/arcgis-rest-request @esri/arcgis-rest-routing --save -
Create a new JavaScript file named
index.js.Use dark colors for code blocks Copy touch index.js
Get an access token
Create a new API key credential with the correct privileges to get an access token.
- Go to the Create an API key tutorial and create an API key with the following privilege(s):
- Privileges:
- Location services > Routing
- Privileges:
- Copy the API key access token to your clipboard when prompted.
Make a request
-
Open your
index.jsfile and import the packages.index.jsUse dark colors for code blocks import { ApiKeyManager } from "@esri/arcgis-rest-request"; import { solveRoute } from "@esri/arcgis-rest-routing"; -
Paste in your access token.
index.jsUse dark colors for code blocks import { ApiKeyManager } from "@esri/arcgis-rest-request"; import { solveRoute } from "@esri/arcgis-rest-routing"; const accessToken = "YOUR_ACCESS_TOKEN"; const authentication = ApiKeyManager.fromKey(accessToken); -
Make a request to the ArcGIS Geocoding service and print the results.
index.jsUse dark colors for code blocks import { ApiKeyManager } from "@esri/arcgis-rest-request"; import { solveRoute } from "@esri/arcgis-rest-routing"; const accessToken = "YOUR_ACCESS_TOKEN"; const authentication = ApiKeyManager.fromKey(accessToken); solveRoute({ stops: [ [-117.195677, 34.056383], [-117.918976, 33.812092] ], authentication }).then((response) => { console.log(JSON.stringify(response, null, 2)); }); -
Save the file, then run it from the terminal.
Use dark colors for code blocks Copy node index.js
You should now see the results printed in your console.
{
"checksum": "rI7WAA6YygA.",
"requestID": "c9d60ae1-8cdd-495f-a5e4-f2e239448050",
"routes": {
"fieldAliases": {
"ObjectID": "ObjectID",
"Name": "Name",
"FirstStopID": "FirstStopID",
"LastStopID": "LastStopID",
"StopCount": "StopCount",
"Total_TravelTime": "Total_TravelTime",
"Total_Kilometers": "Total_Kilometers",
"Total_Miles": "Total_Miles",
"Shape_Length": "Shape_Length"
},
What's next?
Learn how to use additional location services in these tutorials: