dace
dace

Reputation: 6363

Global variables are undefined within function scope

I've got this bit of code where the variables latitude and longitude are declared outside of and then defined inside of the positionSuccess function. I would like to re-use these variables later on, but they keep returning as undefined. Not sure why.

I thought if they are defined outside of a function then they should be available within that same scope to other functions. Am I missing something here?

$(document).ready(function(){

  navigator.geolocation.getCurrentPosition(positionSuccess, positionError);

  // Gets the user's location

  var latitude;
  var longitude;

  function positionSuccess(position){
    latitude = position.coords.latitude;
    longitude = position.coords.longitude;
  }

  function positionError(error){
    console.warn('ERROR: ' + error.code + ': ' + error.message);
  }

  // Other functions that need access to latitude and longitude variables.

)};

Thanks for any help!

Upvotes: 0

Views: 80

Answers (1)

jfriend00
jfriend00

Reputation: 707318

Welcome to asynchronous programming in Javascript. Because code is not executed sequentially from top to bottom in your function, asynchronous callbacks require a different method of writing code where results they receive must be processed inside the callbacks, not outside the callbacks.

positionSuccess and positionError are asynchronous callbacks. They are called long AFTER your $(document).ready() handler is DONE executing. As such, the latitude and longitude variables are not yet set when you are trying to use them.

Any code that needs the results inside of positionSuccess() must be placed inside that callback function or you can call some other function and pass the result variable sto it.

$(document).ready(function(){

  navigator.geolocation.getCurrentPosition(positionSuccess, positionError);

  function positionSuccess(position){
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    // insert code to use the latitude and longitude variables here
  }

  function positionError(error){
    console.warn('ERROR: ' + error.code + ': ' + error.message);
  }

  // the latitude and longitude data is not yet available here because 
  // positionSuccess() is called in the future AFTER this part of 
  // the code executes

)};

Upvotes: 5

Related Questions