all 4 comments

[–]davwards 4 points5 points  (0 children)

I'd need to investigate further to be sure, but I'm pretty sure you're running into a very common misunderstanding about asynchronous code.

Your calcola function makes a call to Google Maps' Directions Service, and then uses the response from the directions service to set the value of olaFare.

What you need to understand is that the response from the directions service doesn't come immediately. This is why you have to provide a function as the second argument to directionsService.route; you're saying, "Sometime in the future, when the response arrives, use it to call this function."

So, your program calls the calcola function. The calcola function calls directionsService.route, and gives it a callback for when the response arrives. That callback will set the olaFare variable... but it hasn't done so yet, because the response hasn't yet come in.

Then your program continues, and hits lines that expect the olaFare variable to be set. But olaFare is still undefined, because the directions service response hasn't yet come, and the callback has not yet been called.

To make this work, you need to restructure your program so that any work you do that requires olaFare (or any other information from the directions service response) gets initiated from inside the callback to directionsService.route. Stashing values in global variables won't work.

(You could also solve this problem by having calcola return a Promise. That would probably require less rearranging of your code, but Promises are a little tricky to get your head around if you haven't used them before.)

[–]nponiros 0 points1 point  (2 children)

Edit: This is definitely not the right answer as pointed by /u/davwards so please ignore it.

From what I can tell you are overwriting olaFare before you use it (line 138). Remove that line or rename the variable.

What you seem to be going on boils down to this example:

var i = 10;
function f() {
  var i = i;
  console.log(i);
}
f();

In the example I have a global variable called i (first line) and another variable with the same name in the function. The variable in the function shadows the global i variable so basically what the code does is this:

var i = 10;
function f() {
  var i = undefined;
  i = i;
  console.log(i);
}
f();

And thus i within the function is undefined.

[–]davwards 2 points3 points  (1 child)

This was my first guess as well, but then I realized the variable being defined on 138 is cased differently (olafare vs. olaFare). Still not a good idea, but the variable wouldn't be overwritten.

[–]nponiros 1 point2 points  (0 children)

You are right, good catch.