Home > Web Front-end > JS Tutorial > body text

Use Google Maps API to get the js code for the distance between points_javascript skills

WBOY
Release: 2016-05-16 17:49:20
Original
1176 people have browsed it
Copy code The code is as follows:

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!
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template