Returning Values from a geolocation API

坚强是说给别人听的谎言 提交于 2021-01-29 13:09:30

问题


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 using the values within the function and they work but i cannot seem to get them to work outside the position function. I need a way to make the "location" object accessible to other functions.

window.navigator.geolocation.getCurrentPosition(
  position => {
    const location = {
      lat:position.coords.latitude,
      long:position.coords.longitude
    }
    return location
  },
  (err)=>console.log(err),

);
console.log(location)

I expect to get the code inside the "location" object located within the position function.Please Help


回答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.
 */
const getLocation = () => new Promise(
  (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));



回答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),

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

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



来源:https://stackoverflow.com/questions/57829690/returning-values-from-a-geolocation-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!