I want the distance by car and train. I can get it from the Google Maps API but when I want the distance in a variable, the function getDistance() with the API returns direct and doesn't wait on the response from the API. On the Internet I found solutions with async/await, promises and callbacks. But it doesn't work for me, probably because I wrote it wrong. But can someone please help me and explain my fault?
Thanks!
My code:
function giveComparing(result) {
var $distanceCar = getDistance(result, google.maps.TravelMode.DRIVING);
var $distanceTrain = getDistance(result, google.maps.TravelMode.TRANSIT);
console.log($distanceCar); // Output: 0
console.log($distanceTrain); // Output: 0
};
function getDistance(result, transport) {
var origin = result.departure.stationinfo.locationY + ',' + result.departure.stationinfo.locationX;
var destination = result.arrival.stationinfo.locationY + ',' + result.arrival.stationinfo.locationX;
var service = new google.maps.DistanceMatrixService();
var distance = 0;
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: [transport]
}, callback);
function callback(response, status) {
console.log(response.rows[0].elements[0].distance.value);
distance = response.rows[0].elements[0].distance.value;
};
return distance;
}