0

So basically this is the code to get users' location, after fetching the data from Promise I can't use it outside, I tried using the push array object but can't use its value. Previously I got help i tried the same thing yet the same problem I m new to js can anyone help with this

let addr = [];
var lati;
var long;

const init = async() => {
  const todo = await geo(1);
  console.log(todo);
};

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    console.log("Geolocation is not supported by this browser.");
  }
}

function showPosition(position) {
  lati = position.coords.latitude;
  long = position.coords.longitude;
  init();
}

const geo = async(id) =>
  new Promise((resolve, reject) => {
    const KEY = "APIKEY";
    const LAT = lati;
    const LNG = long;
    let url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${LAT},${LNG}&key=${KEY}`;

    fetch(url)
      .then((response) => response.json())
      .then((data) => {
        resolve(data);
        console.log(data);
        addr.push(data.results[0].formatted_address);
      })

      .catch((err) => console.warn(err.message));
  });

window.onload = getLocation();
console.log(addr[0]);
Manas Khandelwal
  • 3,790
  • 2
  • 11
  • 24
  • You are logging the contents of `addr` array _before_ it is populated. Also, `fetch` already returns a promise, so don't use the promise constructor to explicitly create a new promise – Yousaf Mar 28 '21 at 11:21
  • Why are you asking same question again and again? – Manas Khandelwal Mar 28 '21 at 11:22

0 Answers0