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 push array object but can't use its value.
let addr = [];
var lati;
var long;
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;
revgeo();
}
function revgeo(){
const KEY = "api";
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 => {
addr.push(data.results[0].formatted_address);
console.log(data);
})
.catch(err => console.warn(err.message));
}
window.onload = getLocation();
console.log(addr); // this works
console.log(addr[0]); // this doesn't work