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 Routing 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 will define an origin and destination by clicking on the map. These values are used to get a route and directions from the route service. The directions are also displayed on the map.
Prerequisites
Steps
Create a new pen
- To get started, either complete the Display a map tutorial or .
Get an access token
You need an access token with the correct privileges to access the location services used in this tutorial.
- Go to the Create an API key tutorial and create an API key with the following privilege(s):
- Privileges
- Location services > Basemaps
- Location services > Geocoding
- Location services > Routing
- Privileges
- In CodePen, set
esri
to your access token.Config.api Key Use dark colors for code blocks var esriConfig = { apiKey: "YOUR_ACCESS_TOKEN" };
To learn about other ways to get an access token, go to Types of authentication.
Add modules
-
In the
require
statement, add theGraphic
,route
,Route
, andParameters Feature
modules.Set The ArcGIS Maps SDK for JavaScript is available as AMD modules and ES modules, but this tutorial is based on AMD. The AMD
require
function uses references to determine which modules will be loaded – for example, you can specify"esri/layers/
for loading the FeatureLayer module. After the modules are loaded, they are passed as parameters (e.g.Feature Layer" Feature
) to the callback function where they can be used in your application. It is important to keep the module references and callback parameters in the same order. To learn more about the API's different modules visit the Overview Guide page.Layer Use dark colors for code blocks require([ "esri/config", "esri/Map", "esri/views/MapView", "esri/Graphic", "esri/rest/route", "esri/rest/support/RouteParameters", "esri/rest/support/FeatureSet" ], function(esriConfig, Map, MapView, Graphic, route, RouteParameters, FeatureSet) {
Update the map
A streets basemap layer is typically used in routing applications. Update the basemap
property to use the arcgis/navigation
basemap layer and change the position of the map to center on Los Angeles.
-
Update the
basemap
property toarcgis/navigation
.Use dark colors for code blocks ], function(esriConfig, Map, MapView, Graphic, route, RouteParameters, FeatureSet) { esriConfig.apiKey = "YOUR_ACCESS_TOKEN"; const map = new Map({ basemap: "arcgis/navigation" // basemap styles service });
-
Update the
center
property to-118.24532,34.05398
and set thezoom
property to12
to center on Los Angeles.Use dark colors for code blocks esriConfig.apiKey = "YOUR_ACCESS_TOKEN"; const map = new Map({ basemap: "arcgis/navigation" // basemap styles service }); const view = new MapView({ container: "viewDiv", map: map, center: [-118.24532,34.05398], //Longitude, latitude zoom: 12 });
Define the service url
The rest module makes a request to a service and returns the results. Use the route
module to access the Routing service.
- Create a variable called
route
to reference the route service.Url Use dark colors for code blocks const view = new MapView({ container: "viewDiv", map: map, center: [-118.24532,34.05398], //Longitude, latitude zoom: 12 }); const routeUrl = "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World";
Get an origin and destination
A route
module uses a stops
parameter to find a route. Stops
are graphics that represent the origin and destination locations for a route. Use a click
handler in the View
to add graphics when the map is clicked. The graphics will define the stops
for the route.
-
Add a
click
handler to add graphics to the view.Use dark colors for code blocks const routeUrl = "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World"; view.on("click", function(event){ });
-
Create an
add
function to display a white marker for the origin location and a black marker for the destination. Add theGraphic graphic
to theview
.Use dark colors for code blocks view.on("click", function(event){ }); function addGraphic(type, point) { const graphic = new Graphic({ symbol: { type: "simple-marker", color: (type === "origin") ? "white" : "black", size: "8px" }, geometry: point }); view.graphics.add(graphic); }
-
Update the
click
handler to reference theadd
function. The first click will create the origin and the second will create the destination. Subsequent clicks will clear the graphics to define a new origin and destination.Graphic Use dark colors for code blocks view.on("click", function(event){ if (view.graphics.length === 0) { addGraphic("origin", event.mapPoint); } else if (view.graphics.length === 1) { addGraphic("destination", event.mapPoint); } else { view.graphics.removeAll(); addGraphic("origin",event.mapPoint); } });
-
Click on the map twice to ensure the graphics are created.
Find the route
To solve the route, add the origin and destination graphics to the stops
parameter as a Feature
and then use the solve
method. The resulting route will be added to the map as a Graphic
.
Input parameters are necessary to solve the route. While there are many parameters you can add, such as stops and barriers, at minimum you need to provide an origin and destination point.
-
Create a
get
function to addRoute Route
and pass in the point graphics.Parameters Use dark colors for code blocks function addGraphic(type, point) { const graphic = new Graphic({ symbol: { type: "simple-marker", color: (type === "origin") ? "white" : "black", size: "8px" }, geometry: point }); view.graphics.add(graphic); } function getRoute() { const routeParams = new RouteParameters({ stops: new FeatureSet({ features: view.graphics.toArray() }), }); }
-
Call the
solve
method to get the route. When the method returns, get the route fromroute
and add it to the view as aResults Graphic
with a blue line.Use dark colors for code blocks function getRoute() { const routeParams = new RouteParameters({ stops: new FeatureSet({ features: view.graphics.toArray() }), }); route.solve(routeUrl, routeParams) .then(function(data) { data.routeResults.forEach(function(result) { result.route.symbol = { type: "simple-line", color: [5, 150, 255], width: 3 }; view.graphics.add(result.route); }); }) }
-
Update the
click
handler with theget
function after the second graphic is passed in (Route destination
).Use dark colors for code blocks view.on("click", function(event){ if (view.graphics.length === 0) { addGraphic("origin", event.mapPoint); } else if (view.graphics.length === 1) { addGraphic("destination", event.mapPoint); getRoute(); // Call the route service } else { view.graphics.removeAll(); addGraphic("origin",event.mapPoint); } });
-
Click two locations on the map to display a route.
Get directions
You can get driving directions from the route service with the return
property on Route
. Use this property to return directions and add them to the map as HTML elements.
-
Go back to the
get
function and set theRoute return
property toDirections true
.Use dark colors for code blocks function getRoute() { const routeParams = new RouteParameters({ stops: new FeatureSet({ features: view.graphics.toArray() }), returnDirections: true }); route.solve(routeUrl, routeParams) .then(function(data) { data.routeResults.forEach(function(result) { result.route.symbol = { type: "simple-line", color: [5, 150, 255], width: 3 }; view.graphics.add(result.route); }); }) }
-
After the
solve
method has resolved, create adirections
ordered list element that will display if there are results returned to generate a route.Use dark colors for code blocks route.solve(routeUrl, routeParams) .then(function(data) { data.routeResults.forEach(function(result) { result.route.symbol = { type: "simple-line", color: [5, 150, 255], width: 3 }; view.graphics.add(result.route); }); // Display directions if (data.routeResults.length > 0) { const directions = document.createElement("ol"); directions.classList = "esri-widget esri-widget--panel esri-directions__scroller"; directions.style.marginTop = "0"; directions.style.padding = "15px 15px 15px 30px"; const features = data.routeResults[0].directions.features; } })
-
Create a
li
element for each route feature to generate an ordered list of directions with their distances in miles. Append eachdirection
to thedirections
element.Use dark colors for code blocks // Display directions if (data.routeResults.length > 0) { const directions = document.createElement("ol"); directions.classList = "esri-widget esri-widget--panel esri-directions__scroller"; directions.style.marginTop = "0"; directions.style.padding = "15px 15px 15px 30px"; const features = data.routeResults[0].directions.features; // Show each direction features.forEach(function(result,i){ const direction = document.createElement("li"); direction.innerHTML = result.attributes.text + " (" + result.attributes.length.toFixed(2) + " miles)"; directions.appendChild(direction); }); }
-
For each new route created, remove all existing HTML elements from the view with the
empty
method. Add thedirection
element, with the directions as list items, to the top-right of the view.Use dark colors for code blocks // Show each direction features.forEach(function(result,i){ const direction = document.createElement("li"); direction.innerHTML = result.attributes.text + " (" + result.attributes.length.toFixed(2) + " miles)"; directions.appendChild(direction); }); view.ui.empty("top-right"); view.ui.add(directions, "top-right");
-
Add a
catch
statement to display any errors in the console.Use dark colors for code blocks route.solve(routeUrl, routeParams) .then(function(data) { data.routeResults.forEach(function(result) { result.route.symbol = { type: "simple-line", color: [5, 150, 255], width: 3 }; view.graphics.add(result.route); }); // Display directions if (data.routeResults.length > 0) { const directions = document.createElement("ol"); directions.classList = "esri-widget esri-widget--panel esri-directions__scroller"; directions.style.marginTop = "0"; directions.style.padding = "15px 15px 15px 30px"; const features = data.routeResults[0].directions.features; // Show each direction features.forEach(function(result,i){ const direction = document.createElement("li"); direction.innerHTML = result.attributes.text + " (" + result.attributes.length.toFixed(2) + " miles)"; directions.appendChild(direction); }); view.ui.empty("top-right"); view.ui.add(directions, "top-right"); } }) .catch(function(error){ console.log(error); })
Run the App
In CodePen, run your code to display the map.
Click on the map twice to display the route directions. The map should support two clicks to create an origin and destination point and then use the route service to display the resulting route and turn-by-turn directions.
What's next?
Learn how to use additional API features and ArcGIS services in these tutorials: