global variable in javascript to get Geolocation

geolocation, html, javascript

Solution

`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
}

Problem

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,

Original source