Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global variable in javascript to get Geolocation

i am using the following code to access the geolocation of the blackberry device. its working and showing the desire result. but i want to access the window.GlobalVar outside the body of this function. how can i access it? please help.

 navigator.geolocation.getCurrentPosition(function(position) {  
  var gps = (position.coords.latitude+position.coords.longitude);  
  window.GlobalVar = gps;
  alert (window.GlobalVar);
});

Best regards,

like image 457
asif hameed Avatar asked Oct 20 '25 05:10

asif hameed


2 Answers

window.GlobalVar will be accessible outside of your function.

What's probably going wrong here is that you're trying to access it before it has been set, seeing as it is being set in a callback function.

getCurrentPosition prompts the user for coordinates, but it is not a blocking call, i.e. it does not simply halt all code execution and wait for the user to make a decision.

This means that you do not set window.GlobalVar during page load, you request it during page load, and you set it whenever the user decides to. So no matter where you call getCurrentPosition you cannot be sure that at a given point, window.GlobalVar will be set.

If you want to be sure that window.GlobalVar is set in the script you're running, you need to make sure that you're running the script after the variable has been set.

navigator.geolocation.getCurrentPosition(function(position) {  
  var gps = (position.coords.latitude+position.coords.longitude);  
  window.GlobalVar = gps;

  continueSomeProcess();
});

function continueSomeProcess() {
   // this code will be able to access window.GlobalVar
}
like image 94
David Hedlund Avatar answered Oct 21 '25 18:10

David Hedlund


Calling window.gps after setting window.gps = gps should be enough as it has a global scope since you attached it to window. Take care of the fact that JS is asynchronous, ie gps might not be defined when you call it.

like image 40
Adrien Avatar answered Oct 21 '25 17:10

Adrien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!