0

I am currently building a ridesharing app on iOS and have run into some issues while using the Google Distance Matrix in my Node.js code.

Below is the code:

distance.matrix(leg3_origin, leg3_destination, function (err, distances) {
               console.log('distance');
               if (err) {
                 console.log(err);
                   return console.log(err);
               }
               else if(!distances) {
                 console.log('no distances..');
                   return console.log('no distances');
               }
               else{
                 console.log('if statement');
                   var origin = distances.origin_addresses[0];
                   var destination = distances.destination_addresses[0];
                       leg3Duration = distances.rows[0].elements[0].duration;
                       leg3Distance = distances.rows[0].elements[0].distance;
                       console.log(leg3Distance);

                       if (leg3Distance == null)
                       {
                         leg3Distance = 0;
                       }
                       console.log('entering 2nd leg');
                       getSecondLeg(driverArrivalTime2, leg3Duration, leg3Distance);

                 }
              });

The line leg3Duration = distances.rows[0].elements[0].duration; is causing the error when trying to call .elements.

I understand it's breaking because leg3Duration is undefined, but it is being initialized in the function. Is there any other way I should be initializing this value to avoid the error?

Thank you for help in advance!

LameBanana
  • 49
  • 4

1 Answers1

0

You should console.log the distances object and confirm that elements is undefined. You might have misspelled elements or maybe you need to use another property?

Other thoughts:

The distance object returned in the callback could resemble something completely different to the documentation in the distance.matrix method.

Maybe the issue is what you passed into the distance.matrix method?

It is hard for us to determine why distances.rows[0] does not contain the elements property as you expected. Are you copying from official documentation or did you manually define the property path to the nested property duration?

SamuelB
  • 157
  • 9
  • Thanks for your quick response! I am defining a couple of variables and passing them manually: I am defining departure_time as: `distance.departure_time(leg3_epoch_arrivalTime2);` and my new destination for example as: `var leg3_destination = [`${obj['endPointLat']}, ${obj['endPointLong']}`];` Every run through of the app yields the departure_time default error message `"departure_time is in the past. Traffic information is only available for future and current times."` – LameBanana Dec 05 '18 at 17:33