I have using google distance matrix api to getting the shortest distance of two geo points from the following way:
Distance Matrix service is asynchronous, for that reason, you need to pass a callback
method to execute upon completion of the request, to process the results. But you could consider to convert async API to promises.
The following example demonstrates how to convert Distance Matrix service API to promises using jQuery:
var origin1 = new google.maps.LatLng(9.6667, 80.0000);
var destinationA = new google.maps.LatLng(9.6689, 80.0059);
function calculateDistances(origins,destinations) {
var service = new google.maps.DistanceMatrixService();
var d = $.Deferred();
service.getDistanceMatrix(
{
origins: origins,
destinations: destinations,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
},
function(response, status){
if (status != google.maps.DistanceMatrixStatus.OK) {
d.reject(status);
} else {
d.resolve(response);
}
});
return d.promise();
}
calculateDistances([origin1],[destinationA])
.done(function(response){
var origins = response.originAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
//console.log(results[j].distance.text);
document.getElementById('result').innerHTML += results[j].distance.text;
}
}
})
.fail(function(status){
document.getElementById('result').innerHTML = 'An error occured. Status: ' + status;
});