An Azure service that provides geospatial APIs to add maps, spatial analytics, and mobility solutions to apps.
The v1 routing service in Azure Maps is using TomTom routing service behind the scenes. I believe this uses a heuristic algorithm when there are more than 10 points in a route to compute the best order. Heuristics like the travelling salesman problem are approximations and may not return the actual best result. The actual best result requires brute force calculations which can be very time consuming and expensive. For 54 waypoints 2916 route paths would need to be calculated just to create the graph, then the shortest path would need to be calculated. This would take a lot of time, much more than the expected response time of this service.
A couple of options:
- Since it appears that if the input waypoints are some what ordered, the results are better, the optimized order using straight lines could be done fairly quickly and used initially before sending the waypoints into the route service.
- Try the Bing Maps Multi-Itinerary Optimization API. Version 2 of the Azure Maps search services use Bing Maps behind the scenes rather than TomTom, which gives Microsoft more control over the algorithms used. More Bing Maps APIs are likely to be exposed through Azure Maps in the future.
- Calculate a route matrix from your points then use a travelling salemen solving algorithm to sort the order. This would give you full control.
I put together a sample for method #1. Since the travelling salesmen algorithm uses heuristics and I'm not doing any sort of caching, the results will change with each calculation since the algorithm uses heuristics which are an approximation. Running he calculation several times I had a best distance of 80KM, I had a few that were around 82KM, most were in the 86 range to 88KM range, and a few where a little over 100KM. Simply running the calculation a couple of times and picking the best result is an option. Here are the details for the best result:
Here is the full code sample I used to test this out. Just add your Azure Maps key near the top of the code:
<!DOCTYPE html>
<html lang="en">
<head>
<title></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" />
<!-- 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.js"></script>
<script type='text/javascript'>
var map, datasource;
var AzureMapsKey = '<Your Azure Maps Key>';
var waypoints = [];
var routeUrl = `https://atlas.microsoft.com/route/directions/json?api-version=1&subscription-key=${AzureMapsKey}&format=json&query={waypoints}&travelMode=car&routeRepresentation=polyline&instructionsType=text&departAt=2023-06-18T23:00:00Z&routeType=shortest`;
function GetMap() {
//Initialize a map instance.
map = new atlas.Map('myMap', {
center: [-74.0004, 40.74746],
zoom: 10,
style: 'grayscale_light',
view: 'Auto',
authOptions: {
authType: 'subscriptionKey',
subscriptionKey: AzureMapsKey
}
});
//Wait until the map resources are ready.
map.events.add('ready', function () {
datasource = new atlas.source.DataSource();
map.sources.add(datasource);
map.layers.add([
new atlas.layer.LineLayer(datasource, null, {
strokeColor: ['get', 'color'],
strokeWidth: 3
}),
new atlas.layer.SymbolLayer(datasource, null, {
iconOptions: {
image: 'marker-red',
ignorePlacement: true,
allowOverlap: true
},
textOptions: {
textField: ['get', 'idx'],
ignorePlacement: true,
allowOverlap: true,
offset: [0, -1.2]
},
filter: ['==', ['geometry-type'], 'Point']
})
]);
});
}
//Parse the waypoint text box and create an array of waypoints.
function getWaypoints() {
var waypointText = document.getElementById('waypointTbx').value;
if (waypointText !== '') {
var waypointArray = waypointText.split('\n');
waypoints = [];
for (var i = 0; i < waypointArray.length; i++) {
var waypoint = waypointArray[i].split(',');
if (waypoint.length >= 2) {
waypoints.push({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [parseFloat(waypoint[1]), parseFloat(waypoint[0])]
},
properties: {
idx: i,
color: 'red'
}
});
}
}
}
}
async function calculate() {
getWaypoints();
datasource.setShapes(waypoints);
if (waypoints.length < 2) {
displayMsg('Not enough valid waypoints specified.');
return;
}
var pointOrder = [];
waypoints.forEach((x, i) => {
pointOrder.push(i);
});
displayMsg('Calculating original order route...<br/><br/>');
await calculateRoute(pointOrder, 'Original order route', 'red');
await calculateRoute(pointOrder, 'Original route with optimizated order', 'purple', true);
displayMsg('Calculating shortest straight line path...', true);
pointOrder = TravellingSalesmen.solve(waypoints, 0.01);
await calculateRoute(pointOrder, 'Optimized straight line TSP order', 'yellow');
displayMsg('Calculating TSP optimized route...', true);
await calculateRoute(pointOrder, 'Optimized TSP route order', 'green', true);
}
async function calculateRoute(pointOrder, routeType, color, computeBestRoute) {
var points = [];
var waypointMap = [];
pointOrder.forEach(i => {
points.push(`${waypoints[i].geometry.coordinates[1]},${waypoints[i].geometry.coordinates[0]}`);
waypointMap[i] = waypoints[i].properties.idx;
});
var routeRequest = routeUrl.replace('{waypoints}', points.join(':'));
if (computeBestRoute) {
routeRequest += '&computeBestOrder=true';
}
var r = await fetch(routeRequest);
var response = await r.json();
if (response.error) {
displayMsg(response.error.message);
return;
}
var route = response.routes[0];
var newPointOrder = new Array(pointOrder.length);
if (response.optimizedWaypoints) {
newPointOrder[0] = 0;
response.optimizedWaypoints.forEach(wp => {
newPointOrder[waypointMap[wp.providedIndex + 1]] = wp.optimizedIndex + 1;
});
newPointOrder[pointOrder.length - 1] = pointOrder.length - 1;
} else {
newPointOrder = pointOrder;
}
displayMsg(`${routeType}: <br/>${newPointOrder.join(', ')}<br/>Distance: ${route.summary.lengthInMeters} meters`, true);
var routeCoordinates = [];
for (var i = 0; i < route.legs.length; i++) {
var leg = route.legs[i];
for (var j = 0; j < leg.points.length; j++) {
routeCoordinates.push([leg.points[j].longitude, leg.points[j].latitude]);
}
}
datasource.add([new atlas.data.Feature(new atlas.data.LineString(routeCoordinates), { color: color })]);
}
function displayMsg(msg, append) {
if (append) {
document.getElementById('output').innerHTML += msg + '<br/><br/>';
} else {
document.getElementById('output').innerHTML = msg;
}
}
class TravellingSalesmen {
constructor(points) {
this.points = points;
this.order = new Array(points.length);
this.distances = new Array(points.length * points.length);
for (var i = 0; i < points.length; i++) {
this.order[i] = i;
for (var j = 0; j < points.length; j++) {
this.distances[j + i * points.length] = distance(points[i], points[j]);
}
}
}
change(temp) {
var i = this.randomPos(), j = this.randomPos();
var delta = this.delta_distance(i, j);
if (delta < 0 || Math.random() < Math.exp(-delta / temp)) {
this.swap(i, j);
}
}
size() {
var s = 0;
for (var i = 0; i < this.points.length; i++) {
s += this.distance(i, ((i + 1) % this.points.length));
}
return s;
}
swap(i, j) {
var tmp = this.order[i];
this.order[i] = this.order[j];
this.order[j] = tmp;
}
delta_distance(i, j) {
var jm1 = this.index(j - 1),
jp1 = this.index(j + 1),
im1 = this.index(i - 1),
ip1 = this.index(i + 1);
var s =
this.distance(jm1, i)
+ this.distance(i, jp1)
+ this.distance(im1, j)
+ this.distance(j, ip1)
- this.distance(im1, i)
- this.distance(i, ip1)
- this.distance(jm1, j)
- this.distance(j, jp1);
if (jm1 === i || jp1 === i)
s += 2 * this.distance(i, j);
return s;
}
index(i) {
return (i + this.points.length) % this.points.length;
}
access(i) {
return this.points[this.order[this.index(i)]];
}
distance(i, j) {
return this.distances[this.order[i] * this.points.length + this.order[j]];
}
randomPos() {
return 1 + Math.floor(Math.random() * (this.points.length - 1));
}
static solve(points, temp_coeff) {
var path = new TravellingSalesmen(points);
if (points.length < 2) return path.order; // There is nothing to optimize
if (!temp_coeff)
temp_coeff = 1 - Math.exp(-10 - Math.min(points.length, 1e6) / 1e5);
for (var temperature = 100 * distance(path.access(0), path.access(1));
temperature > 1e-6;
temperature *= temp_coeff) {
path.change(temperature);
}
return path.order;
}
}
function distance(p, q) {
return atlas.math.getDistanceTo(p, q);
}
</script>
<style>
html, body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
overflow: hidden;
}
#myMap {
position: relative;
width: calc(100% - 355px);
height: 100%;
float: left;
}
.sidePanel {
width: 325px;
padding: 10px;
height: 100%;
float: left;
margin-right: 10px;
}
#output {
height: 40%;
width: 320px;
overflow-y: auto;
}
textarea {
height: 30%;
width: 250px;
}
</style>
</head>
<body onload="GetMap()">
<div class="sidePanel">
<h1 style="font-size:16px">Optimized routes</h1>
<p>
This sample calculates an approximate shortest path based on straightline distances to pre-order the waypoints,
then uses the Azure Maps Route API to calculate the actual route.
</p>
Waypoints: <br />
<textarea id="waypointTbx">
40.74407,-73.97668
40.77237,-73.9886
40.77189,-73.98859
40.76726,-73.98754
40.76718,-73.98812
40.76658,-73.98669
40.76453,-73.987
40.75586,-73.96645
40.76258,-73.99311
40.76199,-73.99258
40.76153,-73.99431
40.75975,-73.99616
40.75,-73.97495
40.74956,-73.97689
40.74593,-73.97111
40.74572,-73.9721
40.74496,-73.98349
40.74353,-73.97943
40.74669,-73.99614
40.74746,-74.0004
40.74398,-73.99243
40.74261,-73.99635
40.74104,-73.99172
40.73699,-73.98135
40.74219,-74.00016
40.73829,-73.989
40.73587,-73.9828
40.73587,-73.9828
40.73484,-73.9804
40.73622,-73.98882
40.73853,-73.99648
40.73856,-73.99695
40.73288,-73.98102
40.73956,-74.0029
40.73631,-73.99636
40.73655,-74
40.73406,-73.99427
40.72924,-73.98084
40.73453,-74.00027
40.72824,-73.98554
40.73323,-74.00619
40.72269,-73.98992
40.72769,-74.00698
40.72591,-74.00342
40.71806,-73.98901
40.72275,-74.01099
40.71834,-74.0092
40.717,-74.00561
40.71675,-74.00997
40.70929,-74.00356
40.70725,-74.00713
40.70743,-74.01222
40.70829,-74.01809
40.90947,-74.2382
</textarea>
<br />
<input type="button" value="Calculate" onclick="calculate()" />
<br /><br />
<b>Log:</b>
<br />
<div id="output"></div>
</div>
<div id="myMap"></div>
</body>
</html>