0

I'm trying to get a object from my getCurrentLocation() method and then I would like to use the coordinates (position.coords.latitude, position.coords.longitude) of this object on my getUserAddressBy() method. I'm calling it from my app.js, but when I console log there, it gets an undefined value, and when I console log directly on the method I get the right object.

Any help, please? I'm totally new on JavaScript programming.

Here is my code.

class GeoLocator {
  constructor(city, country) {
    this.keyUser = "";
    this.city = city;
    this.country = country;
  }

  async getUserAddressBy(lat, long) {
    const location = await fetch(`https://maps.googleapis.com/maps/api/geocode/json? 
  latlng=${lat},${long}&key=${this.keyUser}`);

    const currentLoc = await location.json();

    this.city = currentLoc.results[0].address_components[3].long_name;
    this.country = currentLoc.results[0].address_components[5].short_name;

    return { city: this.city, country: this.country };
  }

  getCurrentLocation() {
    self = this;
    return navigator.geolocation.getCurrentPosition(position => {
      console.log(position);
      return position;
    });
  }
}

// My app.js file
const currentLocation = new GeoLocator();
console.log(currentLocation.getCurrentLocation());
Always Learning
  • 5,510
  • 2
  • 17
  • 34
Vssmm
  • 51
  • 7
  • the function `navigator.geolocation.getCurrentPosition` immediately returns `undefined` - the callback `position => ...` is called asynchronously at some time in the future – Bravo Nov 05 '19 at 21:57

2 Answers2

0

getCurrentPosition function is not invoked immediately.

Refer to this General asynchronous programming concepts to fully understand what Async Programming is.

Then read about Callback function

Rafi Henig
  • 5,950
  • 2
  • 16
  • 36
0

In Javascript many operations are done asynchronously, meaning the function returns before the operation is done and you have to handle the result later through either a: * callback function which gets called when the operation is complete * Promise that gets resolved/rejected when the operation is complete. In the case of the navigator.geolocation.getCurrentPosition function it uses a callback function which you have provided. That means the function that you provided as the parameter to the call will get invoked when the data is ready.

In your code you returned the value from getCurrentPosition which returns instantly with a value of undefined. That explains why you see undefined in the last console.log in your sample code.

Typically you'd handle this by your function also having a callback parameter and you will call that when you have the necessary data like this:

getCurrentLocation(callback) {
  navigator.geolocation.getCurrentPosition(position => {
    console.log(position);
    return callback(position);  // send back the result to your caller
  });
}

//  then from outside you can call it like this:
const currentLocation = new GeoLocator();
currentLocation.getCurrentLocation(data => {
  console.log(data);
});

I recommend that you read more about Javascript's concept of callbacks and Promises to get a good understanding of the asynchronous nature of the language. It's quite powerful but can take some getting used to.

Here's how you could do a similar thing using a Promise:

getCurrentLocation() {
  return new Promise((resolve,reject) => {
    navigator.geolocation.getCurrentPosition(
      position => {
        console.log(position);
        return resolve(position);  // send back the result to your caller
      },
      error => return reject(error) // report an error
    }
  );
}

//  then from outside you can call it like this:
const currentLocation = new GeoLocator();
currentLocation.getCurrentLocation()
  .then(data => {
    console.log(data);   // only happens after the promise resolves
  })
  .catch(err => console.error(error));
Always Learning
  • 5,510
  • 2
  • 17
  • 34
  • You've definitelly made my day! I've really appreciated that answer! I was stuck for about few days, also getting really frustrated with programming... Thanks a lot for that complete answer for a begginer like me, I'm pretty sure your answer gonna help loads of people. – Vssmm Nov 05 '19 at 23:05
  • How could I use the value data outside this of this call currentLocation.getCurrentLocation(data => {console.log(data);}); – Vssmm Nov 06 '19 at 11:37
  • In the example above, I used it to do the `console.log(data)` so just put whatever you want to do in that first function in the `.then` – Always Learning Nov 06 '19 at 17:16