This is a simple question, but I can’t work it out.
The specifics aren’t important, but here’s the gist. I have some code like this:
var lat = 0;
var lon = 0;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
});
}
What I think it’s doing is:
- Set lat and lon to 0
- If the browser has geolocation, overwrite those variables with real values
However, at the end of that chunk, lat and lon are still 0. I’ve tried adding vars, passing lat and lon to the function etc but with no success…
How do I make this work?
It’s an async callback. Basically, you pass a function to the the navigator API. Then, your code continues (and does whatever). Later, the navigator API calls your callback with the answer (position). Thus, anything that uses position must be inside (including called by) the callback.
See also this previous answer, which shows how you can create and use a wrapper function.
EDIT: You can simply write a function that calls your callback regardless. If you wanted, getLocation could pass another flag to its argument (e.g. a failure/success code).
Then later:
You don’t have to use anonymous functions.