Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
177 lines (144 sloc) 7.73 KB
<!DOCTYPE html>
<html>
<head>
<title>Route Waypoint Optimization - Azure Maps Web SDK Samples</title>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="IE=Edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="This sample shows how to calculate routes with and without waypoint optimization using the Azure Maps REST Route API." />
<meta name="keywords" content="map, gis, API, SDK, route directions service, direcitons, travelling salesmen problem, route optimization, optimize, vehicle routing problem, VRP, TSP" />
<meta name="author" content="Microsoft Azure Maps" />
<!-- Add references to the Azure Maps Map control JavaScript and CSS files. -->
<link rel="stylesheet" href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.css" type="text/css" />
<script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.js"></script>
<script type='text/javascript'>
var map, datasource, routeLine, waypointQuery, defaultOrder;
var restRoutingRequestUrl = 'https://atlas.microsoft.com/route/directions/json?api-version=1&subscription-key={subscription-key}&query={query}&routeRepresentation=polyline&travelMode=car&view=Auto';
var waypoints = [
[-122.336502, 47.606544],
[-122.204821, 47.759892],
[-122.120415, 47.670682],
[-122.213369, 47.480133],
[-122.193689, 47.615556],
[-122.206054, 47.676508],
[-122.360861, 47.495472]
];
function GetMap() {
//Initialize a map instance.
map = new atlas.Map('myMap', {
center: [-122.216217, 47.619383],
zoom: 9,
view: 'Auto',
//Add your Azure Maps subscription key to the map SDK. Get an Azure Maps key at https://azure.com/maps
authOptions: {
authType: 'subscriptionKey',
subscriptionKey: '<Your Azure Maps Key>'
}
});
//Wait until the map resources are ready.
map.events.add('ready', function () {
//Create a data source to store the data in.
datasource = new atlas.source.DataSource();
map.sources.add(datasource);
//Add layers fro rendering data in the data source.
map.layers.add([
//Render linestring data using a line layer.
new atlas.layer.LineLayer(datasource, null, {
strokeColor: 'blue',
strokeWidth: 5
}),
//Render point data using a symbol layer.
new atlas.layer.SymbolLayer(datasource, null, {
textOptions: {
textField: ['get', 'title'],
offset: [0, -1.2],
color: 'white'
},
filter: ['any', ['==', ['geometry-type'], 'Point'], ['==', ['geometry-type'], 'MultiPoint']] //Only render Point or MultiPoints in this layer.
})
]);
//Add waypoints to the map and build the waypoint query string.
var points = [];
var query = [];
defaultOrder = [];
for (var i = 0; i < waypoints.length; i++) {
points.push(new atlas.data.Feature(new atlas.data.Point(waypoints[i]), {
title: i + ''
}));
query.push(waypoints[i][1] + ',' + waypoints[i][0]);
defaultOrder.push(i);
}
//Add the points to the data source.
datasource.add(points);
//Create the waypoint query string value to be used in the routing requests.
waypointQuery = query.join(':');
});
}
function calculateRoute(optimized) {
//Remove any previously calculated route information.
if (routeLine) {
datasource.remove(routeLine);
routeLine = null;
document.getElementById('output').innerHTML = '';
}
//Create request to calculate a route in the order in which the waypoints are provided.
var requestUrl = restRoutingRequestUrl.replace('{subscription-key}', atlas.getSubscriptionKey()).replace('{query}', waypointQuery);
if (optimized) {
requestUrl += '&computeBestOrder=true';
}
//Proces the request.
fetch(requestUrl)
.then(function (response) {
return response.json();
}).then(function (r) {
addRouteToMap(r.routes[0]);
var output = 'Distance: ' + Math.round(r.routes[0].summary.lengthInMeters / 10) / 100 + ' km<br/>';
if (optimized) {
var pinOrder = ['0'];
for (var i = 0; i < r.optimizedWaypoints.length; i++) {
//Increase index by one to account for origin index.
pinOrder.push(r.optimizedWaypoints[i].optimizedIndex + 1);
}
//Add the desintation index to the end.
pinOrder.push(waypoints.length - 1);
output += 'Waypoint Order: ' + pinOrder.join(', ');
} else {
output += 'Waypoint Order: ' + defaultOrder.join(', ');
}
document.getElementById('output').innerHTML += output;
});
}
function addRouteToMap(route) {
var routeCoordinates = [];
for (var legIndex = 0; legIndex < route.legs.length; legIndex++) {
var leg = route.legs[legIndex];
//Convert the route point data into a format that the map control understands.
var legCoordinates = leg.points.map(function (point) {
return [point.longitude, point.latitude];
});
//Combine the route point data for each route leg together to form a single path.
routeCoordinates = routeCoordinates.concat(legCoordinates);
}
//Create a LineString from the route path points and add it to the data source.
routeLine = new atlas.Shape(new atlas.data.LineString(routeCoordinates));
datasource.add(routeLine);
}
</script>
</head>
<body onload="GetMap()">
<div id="myMap" style="position:relative;width:100%;min-width:290px;height:600px;"></div>
<div style="position:absolute;top:15px;left:15px;background-color:white;padding:10px;border-radius:10px;">
<input type="button" value="Calculate Route" onclick="calculateRoute()" />
<input type="button" value="Calculate Waypoint Optimized Route" onclick="calculateRoute(true)" />
<br /><br />
<div id="output"></div>
</div>
<fieldset style="width:calc(100% - 30px);min-width:290px;margin-top:10px;">
<legend>Route Waypoint Optimization</legend>
This sample shows how to calculate routes with and without waypoint optimization using the Azure Maps REST Route API.<br /><br />
<b>Note:</b> The optimized waypoint order information from the routing service provides a set of indices.
These exclude the origin and destination indices.
You need to increase all of these values by 1 to account for the origin and then add your destination to the end to get the complete ordered waypoint list.
</fieldset>
</body>
</html>
You can’t perform that action at this time.