Skip to content

Instantly share code, notes, and snippets.

@PixelJunkie33
Created April 23, 2019 20:06
Show Gist options
  • Save PixelJunkie33/5c885bf779efdfd437f55406f10e867c to your computer and use it in GitHub Desktop.
Save PixelJunkie33/5c885bf779efdfd437f55406f10e867c to your computer and use it in GitHub Desktop.
Get a route and directions
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<title>ArcGIS JavaScript Tutorials: Create a Starter App</title>
<style>
html, body, #viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
</style>
<link rel="stylesheet" href="https://js.arcgis.com/4.11/esri/css/main.css">
<script src="https://js.arcgis.com/4.11/"></script>
<script>
require([
"esri/Map",
"esri/views/MapView",
"esri/tasks/RouteTask",
"esri/tasks/support/RouteParameters",
"esri/tasks/support/FeatureSet",
"esri/Graphic"
], function(Map, MapView, RouteTask, RouteParameters, FeatureSet, Graphic) {
var map = new Map({
basemap: "streets-navigation-vector"
});
var view = new MapView({
container: "viewDiv",
map: map,
center: [-118.80543,34.02700],
zoom: 12
});
var routeTask = new RouteTask({
url: "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World"
});
view.on("click", function(event){
if (view.graphics.length === 0) {
addGraphic("start", event.mapPoint);
} else if (view.graphics.length === 1) {
addGraphic("finish", event.mapPoint);
// Call the route service
getRoute();
} else {
view.graphics.removeAll();
addGraphic("start",event.mapPoint);
}
});
function addGraphic(type, point) {
var graphic = new Graphic({
symbol: {
type: "simple-marker",
color: (type === "start") ? "white" : "black",
size: "8px"
},
geometry: point
});
view.graphics.add(graphic);
}
function getRoute() {
// Setup the route parameters
var routeParams = new RouteParameters({
stops: new FeatureSet({
features: view.graphics.toArray() // Pass the array of graphics
}),
returnDirections: true
});
// Get the route
routeTask.solve(routeParams).then(function(data) {
// Display the route
data.routeResults.forEach(function(result) {
result.route.symbol = {
type: "simple-line",
color: [5, 150, 255],
width: 3
};
view.graphics.add(result.route);
});
});
}
});
</script>
</head>
<body>
<div id="viewDiv"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment