0

I'm have C++ and Java background. I'm having some trouble understanding function calling in JavaScript.

Below is my code example, I declared variable lon and lat #4. and assign it value on line #5 and #6.

Here is my question, I made a call to writeToTes() on #1 and it worked. But when I placed writeToTes() on #2 or #3, lon and lat is empty, like it was never assigned. Why is that?

according to my logic, we already executed if(navigator.geolocation){}, lat and lon should already be assigned, why is it when I made call to writeToTes() lon and lat is still empty.

var lon = '',
  lat = ''; // #4 

$(document).ready(function() {
  setLonLat();
});

function setLonLat() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      lat = (position.coords.latitude); //#5
      lon = (position.coords.longitude); //#6
      writeToTes(); //#place it Here  #1
    });
    //#place it Here  #2
  }
  //#place it Here  #3
}

function writeToTes() {
  $("#tes").html(lon + " " + lat);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
Fei.Fly
  • 25
  • 3
  • 2
    That's because of asynchronicity, that's why you pass the callback function - it get's called when the result is received. If you place the variable outside of the callback handler, you'll see it's state before something was assigned – baao Feb 27 '17 at 21:02

2 Answers2

6

It's because getCurrentPosition() is an asynchronous operation. The function you pass to getCurrentPosition() is called a callback function. Any code put into this function is executed after the current position is retrieved.

When you place writeToTest() after the call to getCurrentPosition(), it is executed BEFORE getCurrentPosition() has finished executing. Therefore, lat and lon have not been assigned to yet.

Steve Adams
  • 2,812
  • 22
  • 29
  • Is there a way to keep the variable that was assigned in the callback function and still be able to access outside of the callback function? – Fei.Fly Feb 27 '17 at 21:17
  • You will still be able to access it outside of the callback function, but this isn't a good thing to do because you don't know when it has been assigned. Hence, you want to execute all code depending on the location within the callback. If you want to make this code more neat, use Promises. – Hadas Zeilberger Feb 27 '17 at 21:19
  • @Hadaz Zeilberger Thank you ! – Fei.Fly Feb 27 '17 at 21:24
0

It is like adding an eventhandler on a button click. The eventhandler will only fire once the button is clicked. In this case, your eventhandler, or callback, is invoked when you get a geolocation. You callback has the position which contains your lat and lon data.

JohanP
  • 5,252
  • 2
  • 24
  • 34