0

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?

Daniel
  • 15
  • 2

1 Answers1

0
navigator.geolocation.getCurrentPosition(showPosition,error,options);

Geolocation.getCurrentPosition - this API takes first parameter as success callback and second optional parameter as error callback.

It asynchronously attempts to obtain the current location of the device. If the attempt is successful, success callback will be invoked.

Since console.log is below getLocation() function. At the time of execution, the asynchronous request may not be completed and success callback not invoked.

So value for lat and long are not filled at that time and undefined is returned.

To wait until the callback function is completed, you can use a flag variable along with setInterval.

<script>
var lat;
var long;
var callBackStatus;
function showPosition(position) {
    callBackStatus = true;
    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) {
    callBackStatus = true;
    console.warn(`ERROR(${err.code}): ${err.message}`);
}

//Function to get location
function getLocation() {
    var weatherText = document.querySelector("#xyz");
    callBackStatus = false;
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition,error);
    } else {
        weatherText.innerHTML = "Error getting location";
    }
    function ErrorCase(error) {
        weatherText.innerHTML = "Couldn't fetch location";
    }
}


window.onload = function(){
        getLocation();
        var interval = setInterval(function() {
            if (callBackStatus) {
                console.log(lat, long);
                clearInterval(interval);
            } else {
                console.log("Waiting for callback");
            }
        }, 50);
    }
    </script>
Arun Kumar
  • 49
  • 5