0

I'm trying to log the location of the user into an array to user later. In trying to check that it's working I found that the whole array would log to the console, but if I try to log just one element in the array I get an error. Was wondering if anyone could help me understand why.

Javascript is below

window.onload = function getLocation() {
    var userlocation = [];
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
      x.innerHTML = "Geolocation is not supported by this browser.";
    }


  function showPosition(position) {
    userlatitude = position.coords.latitude;
    userlongitude = position.coords.longitude;
    userlocation.push(userlatitude);
    userlocation.push(userlongitude);
  }

    console.log(userlocation[0]);
    console.log(userlocation);
}

I would expect console.log(userlocation[0]) to output the userlatitude but it is coming out as undefined.

  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas Dec 27 '18 at 20:04
  • Welcome. I suggest that you display what the array looks like, so that people can better understand how to help you. – Tedinoz Dec 27 '18 at 20:06

1 Answers1

0

navigator.geolocation.getCurrentPosition is asynchronous. At the time your console statements are executed, the array hasn't been populated yet. The reason it looks like the full array is being logged in the console is because your browser's dev tools are displaying a pointer to the array object, not the contents of the array at the time of the console statement.

If you want to ensure that you have the values provided by the getCurrentPosition function, you should put the code that relies on them in the success callback:

window.onload = function getLocation() {
    var userlocation = [];
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
      x.innerHTML = "Geolocation is not supported by this browser.";
    }


  function showPosition(position) {
    userlatitude = position.coords.latitude;
    userlongitude = position.coords.longitude;
    userlocation.push(userlatitude);
    userlocation.push(userlongitude);

    console.log(userlocation[0]);
    console.log(userlocation);
  }
}
collinksmith
  • 560
  • 1
  • 5
  • 14