Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
Assigning map co ordinates in javascript returns undefined
(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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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();

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda