var request;
var distanceArray = [];
function getdistance() {
distanceArray = [];
var directionsService = new google.maps.DirectionsService();
for (var a = 0; a < pointsArray.length; a ) {
for (var b = 0; b < pointsArray.length; b ) {
if (a != b) {
request = null;
request = {
origin: pointsArray[a ],
destination: pointsArray[b],
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.DirectionsUnitSystem.METRIC
};
directionsService.route(request , function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var myRoute = response.routes[0].legs[0].distance.value; //Route Length
distanceArray.push(myRoute);
}
});
}
}
}
}
Have a question Let me share with you, when using Google Maps API to obtain the distance between batches of points, how to ensure that the distance information you get is in order?
For example: there are three points a, b, c in pointsArray[]. How can I get [a, b], [a, c], [b, a], [ in order? b,c],[c,a],[c,b] distance information.
In the above code, all the distances of a!=b are passed to directionsService.route for solution at one time, that is to say, the peripheral FOR loop control is of no use to it. So the expectation of relying on the FOR loop to obtain the distances one by one failed. However, if you add debugging and control the loop solving process step by step, you can get an ordered distance array. I can’t understand it!