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,
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,
Share Improve this question asked Jul 23, 2012 at 9:42 asif hameedasif hameed 1631 gold badge3 silver badges13 bronze badges 1- Please see stackoverflow./questions/7809690/… – Felix Kling Commented Jul 23, 2012 at 9:51
2 Answers
Reset to default 8window.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
}
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.