-1

I'm trying to put my geolocation inside a variable to use in multiple places throughout my code. I've tried a couple ways of doing this but can't find one that works. Here is what I am currently trying but it always returns undefined. Does anyone know how to do this?

const getLocation  = () => {
    let position;

    navigator.geolocation.getCurrentPosition(location => {
      position = location;
    });

    return position;
};

Well I figured out how to make this work but it's currently flagged as a repeat post for another post that has nothing to do with this. What worked for me was passing the position as an argument into another function.

const init = () => {
    navigator.geolocation.getCurrentPosition(function(position) {
        loader.load().then(() => {
            initMap(position);
        });
    });
};

The loader.load is for the google maps api.

  • `navigator.geolocation.getCurrentPosition` is asynchronous, the value of location is not available when the `getLocation` function returns. – geocodezip Feb 02 '22 at 19:31

1 Answers1

1

I would clean up your code to use a Promise. Also should use the error callback... https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition#examples

const getLocation  = async () => {
    return new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(
        resolve, 
        (err) => {   
          console.warn(`ERROR(${err.code}): ${err.message}`);
          resolve(undefined)}, // might want to reject depending on error 
        {}, // options
      );
    });
};
const location = await getLocation();
if (location) // do something
Justin Poehnelt
  • 2,992
  • 1
  • 19
  • 23