I am trying to modify variables declared outside any function scope, within the function, however the variables remain undefined. I am triggering the function using window.onload.
Here is the JS code:
var lat;
var long;
function showPosition(position) {
  lat = position.coords.latitude;
  long = position.coords.longitude;
  const apikey_gmaps = "xyz";
  fetch("https://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&key="+apikey_gmaps)
  .then(
    function(response){
      if (response.status !== 200){
        console.log("Error while getting location");
        return;
      }
      response.json().then(function(address){
        var parsedAddress = address.results[0].formatted_address;
        var city = address.results[0].address_components[0].long_name;
      });
    }
  )
    .catch(function(err){
      console.log(err);
    });
}
function error(err) {
    console.warn(`ERROR(${err.code}): ${err.message}`);
  }
//Function to get location
function getLocation() {
  var weatherText = document.querySelector("#xyz");
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition,error,options);
  } else {
    weatherText.innerHTML = "Error getting location";
  }
  function ErrorCase(error) {
    weatherText.innerHTML = "Couldn't fetch location";
  }
}
window.onload = function(){
     getLocation();
     console.log(lat,long);
     }
This logs undefined undefined in the console. However, if I call the functions in my Chrome dev console directly (without onload), it works pretty fine.
I have tried using body onload="someFn()", tried declaring the variables inside onload=function(){}, without any success.
How can I modify these global variables?
 
    