0

I am trying to use javascript to get a user's geolocation so i can then use that information as a parameter in another section of javascript code, however I can't get the scope right.

This is my code. Doing the alert inside the success function works fine, but if i try to access var lat anywhere outside the function, i get undefined value. How would I go about fixing this?

var lat; var long;
function success(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
alert(lat);
}

function error(msg) {

}

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(success, error);

} else {
  error('not supported');
}
3
  • Welcome to the wonderful world of async! You can't do that. Commented Feb 3, 2012 at 0:37
  • I don't see where you are trying to reference lat outside of success(). Commented Feb 3, 2012 at 0:43
  • @gilly3 - i had it after the if else statement, then moved it inside the success function. It only works inside the success function. I guess I'm looking for some way of waiting till the value is returned before trying to access it Commented Feb 3, 2012 at 0:45

1 Answer 1

1

You want your code to work like this:

navigator.geolocation.getCurrentPosition(success, error); 
alert("Your position is " + lat + ", " + long + ".");
// do some more stuff with lat and long

But, success() has not been called yet, so lat is still undefined. That's what your success handler is for. All the code that needs to be executed after you've retrieved the location goes in the success handler. This would work:

navigator.geolocation.getCurrentPosition(function (position) {
    success(position);
    alert("Your position is " + lat + ", " + long + ".");
    // do some more stuff with lat and long
}, error);
Sign up to request clarification or add additional context in comments.

Comments

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.