0

I'm trying to write function that returns the geolocation using html5. However my function never returns. How come?

function getCurLocation() {
    navigator.geolocation.getCurrentPosition(function(position) {  
        return [position.coords.latitude, position.coords.longitude];
    });
}
2
  • add a return before navigator.geolocation. Commented May 20, 2013 at 2:07
  • @karthikr I also tried that. Commented May 20, 2013 at 2:08

1 Answer 1

2

navigator.geolocation.getCurrentPosition is an asynchronous call. As with all Ajax, you can't return it's value synchronously with the rest of the code. You can't know when it will complete or even if it will complete. Any work that relies on the response (position in this case) of the ajax call must be done in the ajax callback.

Sign up to request clarification or add additional context in comments.

6 Comments

Is there anyway to wait until it completes to return?
@drum as far as I can tell you can't, but why would you want to? That would lock up the browser until the operation completed
My application initially gets the current user location. However the user can change its location later on. I don't want the location to reset back to the current location every time the page refreshes.
@drum then store their chosen location in a cookie or something
@drum yes (they are) and no (it doesn't, really) since cookies are an HTTP construct rather than a php or JavaScript one
|

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.