4

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,

1

2 Answers 2

8

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

i am setting it onload, and trying to access it at the end of the page.
@asifhameed: No, you are not setting it onload, you are asking for it onload. When you get it is out of your control, and you may never get it, if the user elects not to share it. At the end of the page it will most likely not be set, because the script at the end of the page will be executed immediately as the site renders, and before the user has a chance to react to the request. See my updated answer.
1

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.

1 Comment

i am setting my global variable onload, and trying to access it at the end of the page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.