Skip to content Skip to sidebar Skip to footer

Returning Values From A Geolocation Api

I am trying to return the longitude and latitude of the user from the geolocation api but so far i keep getting errors when i try to use them outside the function. I have tried usi

Solution 1:

You could wrap your function inside a Promise and wait for it to resolve. This way you can extract the values whenever they become available using the then method. It is kind of similar to adding a callback but it works differently.

So the code below here does not execute here on SO for security reasons, but it will in your own file.

The Promise can take a callback function with 2 parameters. resolve and reject.

resolve could be seen as something like return. But instead of returning the value it stores it in the Promise and changed the state of the Promise to resolved. When that happens all adjecent then methods will be called.

reject is when an error occurs or you simply don't want the Promise to resolve. It calls the adjecent catch block after the Promise statement.

In the then and catch blocks you can access your resolved or rejected values.

Check out more examples in this Medium article.

/**
 * Wrap function in a Promise.
 * Resolve when position is found.
 * Reject when error occurs.
 */constgetLocation = () => newPromise(
  (resolve, reject) => {
    window.navigator.geolocation.getCurrentPosition(
      position => {
        const location = {
          lat:position.coords.latitude,
          long:position.coords.longitude
        };
        resolve(location); // Resolve with location. location can now be accessed in the .then method.
      },
      err =>reject(err) // Reject with err. err can now be accessed in the .catch method.
    );
  }
);

/**
 * then is called when the Promise is resolved
 * catch is called when the Promise rejects or encounters an error.
 */getLocation()
    .then(location =>console.log(location))
    .catch(error =>console.log(error));

Solution 2:

The HTML5 API getcurrentPosition is assync, the easiest way to use the location, is to use a callback function, like this:

window.navigator.geolocation.getCurrentPosition(
  position => {
    const location = {
      lat:position.coords.latitude,
      long:position.coords.longitude
    }
    showLocation(location); // <- Function that will use location data
  },
  (err)=>console.log(err),

);
functionshowLocation(location) {
    console.log(location);
    //other stuff    
}

this link can help to understand better: https://developer.mozilla.org/en-US/docs/Glossary/Callback_function

Post a Comment for "Returning Values From A Geolocation Api"