javascriptnode.jsgoogle-distancematrix-apidistance-matrix

Not able to access value of variable derived from google distance matrix function


I am using Google distance matrix api to get the distance between two locations. I declared a variable globally. Changed this variable in function. But as per normal circumstances I should be able to access this changed value of variable after calling my function. But now I am not being able to access the changed value of variable. My code is:

var distance = require('google-distance-matrix');

var origins = ['San Francisco CA'];
var destinations = ['New York NY'];

distance.key('My API key');
distance.units('imperial');
// my global variabel
let ourdistance;

function getdistance(){ distance.matrix(origins, destinations, function (err, distances) {
     for (var i=0; i < origins.length; i++) {
            for (var j = 0; j < destinations.length; j++) {
                var origin = distances.origin_addresses[i];
                var destination = distances.destination_addresses[j];
                if (distances.rows[0].elements[j].status == 'OK') {
                    var distance = distances.rows[i].elements[j].distance.text;
                    console.log("This is the distance covered "+ distance);
                    //changing global variable value inside function
                    ourdistance=distance}}}});}

// calling function                    
getdistance();

console.log("finale distance is "+ ourdistance);

Result that I got is:---- "finale distance is undefined" "This is the distance covered 2,903 mi"

Now I don't know that why "This is the distance covered 2,903 mi" is coming first and why I can't get the changed value of variable


Solution

  • This is the expected behaviour. console.log("finale distance is "+ ourdistance); is executing before getdistance() is finished. So, you have to console.log inside the callback.

    Example:

    async function main() {
      const util = require('util');
      const matrix = util.promisify(distance.matrix);
    
      async function getdistance() {
        let ourdistance;
        const distances = await matrix(origins, destinations);
        for (var i = 0; i < origins.length; i++) {
          for (var j = 0; j < destinations.length; j++) {
            var origin = distances.origin_addresses[i];
            var destination = distances.destination_addresses[j];
            if (distances.rows[0].elements[j].status == 'OK') {
              var distance = distances.rows[i].elements[j].distance.text;
              console.log("This is the distance covered " + distance);
              ourdistance = distance
            }
          }
        }
    
        return ourdistance;
      }
    
      // calling function                    
      let ourdistance = await getdistance();
    
      console.log("finale distance is " + ourdistance);
    }
    
    main();