Home > front end >  Assigning map co ordinates in javascript returns undefined
Assigning map co ordinates in javascript returns undefined

Time:10-24

(async ( ) =>  {
    async function foo() {
        navigator.geolocation.getCurrentPosition(success, error, options)
        {
            var options = {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
            };
            
            function success(pos) {
            var crd = pos.coords;
            console.log('Your current position is:');
            console.log(`Latitude : ${crd.latitude}`);
            lat = crd.latitude;
            console.log(`Longitude: ${crd.longitude}`);
            long = crd.longitude;
            console.log(`More or less ${crd.accuracy} meters.`);
            return [lat, long];
            }
            
            function error(err) {
            console.warn(`ERROR(${err.code}): ${err.message}`);
            }
        };
    };
})
    

let result = await foo();
console.log(result);

 x = await result[1]
    console.log(x);

I was trying to grab map co-ordinates fom browser and assign them to variables so as to compare to other co-ordinates and find the proxmity to a place. but it keeps returning un

CodePudding user response:

It's not clear from your question where these "other" co-ordinates are coming from, whether they're hard-coded, or loaded from cookies, or localStorage, but this example gets the co-ordinates and saves them to an array which is then saved to localStorage which is loaded whenever the page is refreshed.

It uses one promise to return the results of the geolocation search, and one async method for the main function.

Note: due to security issues this won't run in a snippet, but it has been fully tested.

const posArr = JSON.parse(localStorage.getItem('pos')) || [];

function getPos(options)  {
  return new Promise((res, rej) => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (pos) => res(pos),
        (err) => rej(logError(err)),
        options
      );
    }
  });
}

function logPos(data) {
  const { accuracy, latitude, longitude } = data.coords;
  console.log('Your current position is:');
  console.log(`Latitude : ${latitude}`);
  console.log(`Longitude: ${longitude}`);
  console.log(`More or less ${accuracy} meters.`);
  posArr.push({ accuracy, latitude, longitude });
  localStorage.setItem('pos', JSON.stringify(posArr));
}

function logError(err) {
  const { code, message } = err;
  console.error(`Error code ${code}: ${message}`);
}

const options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

async function main(options) {
  try {
    const response = await getPos(options);
    if (response) {
      logPos(response);
      console.log(posArr);
    }
  } catch (err) {
    console.log('Position not available.');
  }
}

main();
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related