0

Good Morning,

I'm having some trouble with the following function.

function getLocation() {
  var geoLat;
  var geoLong;
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(geo) {
        geoLat = geo.coords.latitude;
        geoLong = geo.coords.longitude;
        console.log(geoLat);
      });
    } else {
      alert("Geolocation information is required for this app to function correctly");
      return false;
    };
  console.log(geoLat);
  return {
    lat: geoLat,
    long: geoLong
  };
};

The first console.log(geoLat) in the if statement returns the correct latitude assigned above it. When I try and reference the geoLat variable again just before the final return it is now undefined. How can an assigned variable change it's value back to undefined without me assigning it or clearing it?

I'm sure this is just me making some form of syntax error. I'm learning JS and don't understand this.

Thanks.

Edit: Now that I've had my mind blown with a 4th dimesion of aync functions I've changed it but still have the following problem

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(geo) {
      var test = geo.coords.latitude;
      console.log(test);
      console.log(geo.coords.latitude);
      return test;
    });
  } else {
    alert("Geolocation information is required for this app to function correctly");
    return false;
  };
}; 

So console.log(test) returns correct coords as does console.log(geo.coords.latitude), however return test; still returns udefined. I'm guessing the result doesn't wait for the async function to finish?

iShaymus
  • 512
  • 7
  • 26
  • This is because navigator.geolocation.getCurrentPosition(...) is asynchronous. This means that console.log(geoLat) before the return statement, is executed before than the asynchronous task is finished. Just move your return statement at the end of navigator.geolocation.getCurrentPosition(function(geo) – Davide Apr 27 '18 at 22:58
  • @Davide would that not then be returning to the `function(geo)` function and not the `function getLocation()`???? – iShaymus Apr 27 '18 at 23:14
  • Take a look. https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition Your function(geo) is just a callback when you receive the coordinates, but when the coordinates arrive you have already executed the console.log(geoLat) before the return statement – Davide Apr 27 '18 at 23:16
  • @Davide see edit to original post. – iShaymus Apr 27 '18 at 23:45
  • Exactly, it doesn't wait. You can adopt one of these solutions. The first, take a look at the Promise JS mechanism. The second one, pass to the getLocation() function a callback function for example getLocation(callback). Replace your return with callback(lat, lon) and create the callback function: function callback(lat, lon) {...} – Davide Apr 28 '18 at 00:03
  • You're welcome :-) – Davide Apr 28 '18 at 00:07

0 Answers0