-2

I am trying to save the result of a function in a variable

let myDistance = (()=>{
   let service = new google.maps.DistanceMatrixService();

   service.getDistanceMatrix(
   {
       origins: [{lat: 55.93, lng: -3.118}],
       destinations: [{lat: 50.087, lng: 14.421}],
       travelMode: google.maps.TravelMode.DRIVING,
       avoidHighways: false,
       avoidTolls: false
   }, callback );

   function callback(response, status) {
         let distance = 0;
         if(status=="OK") {
             distance = response.rows[0].elements[0].distance.value;
         } else {
             alert("Error: " + status);
         }
         return distance;
   }
})();
console.log(myDistance)

But not working I use Google Maps Api v3 - Distance Matrix section

<script async defer
   src="https://maps.googleapis.com/maps/api/jskey=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk">
</script>
magnum888
  • 23
  • 1
  • 4

1 Answers1

0

myDistance variable always will be undefined, you're defining a function and call them immediately to assign it's return value to myDistance variable. but there is nothing back from this function. also you may notice that calling google api is an async function and you're expected result return when work is done by google, then you can't know when response is ready. console.log(myDistance) immediately run after your function and will not wait for response from google api, if you want to see result from google use console.log inside callback function or use async await to waiting for result.

Ali Shabani
  • 428
  • 2
  • 10