sanfranciscoave
sanfranciscoave

Reputation: 5

accessing variable value outside of function

I have 2 functions in my script. The purpose of function #1 is to produce a url called "mapsURL"

The purpose of the second function is to run an .ajax request with "mapsURL"

However I am having issues with accessing "mapsURL" in the second function. I declared "mapsURL" in the first function without a "var" in fornt of it. From my understanding, this should make the this the value global and I should be able to access it form inside other functions. Is my understanding incorrect or what am I missing here?

here's my js:

note: I removed my API key for this post, so that's not the issue

$(document).ready(function (){


  navigator.geolocation.getCurrentPosition(function (position) {
     var positionLat = position.coords.latitude
     var positionLon = position.coords.longitude
     mapsURL = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + positionLat + "," + positionLon + "&key=***mykeygoeshere***";
  });


 function getData (){
   $.ajax({
     url: mapsURL,
     dataType: 'json',
     success: function(response){
      console.log(response);
     }
    });
  };

  getData();

});

Upvotes: 0

Views: 47

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

getCurrentPosition is asynchronous. It doesn't assign to mapsURL immediately, so when you call getData synchronously, mapsURL hasn't been populated yet.

You should call getData inside the getCurrentPosition callback - which will also allow you to avoid using a global variable:

$(document).ready(function() {
  navigator.geolocation.getCurrentPosition(function(position) {
    var positionLat = position.coords.latitude
    var positionLon = position.coords.longitude
    var mapsURL = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + positionLat + "," + positionLon + "&key=***mykeygoeshere***";
    getData(mapsURL);
  });
  function getData(mapsURL) {
    $.ajax({
      url: mapsURL,
      dataType: 'json',
      success: function(response) {
        console.log(response);
      }
    });
  }
});

Upvotes: 4

Related Questions