Variable scope in javascript
- by Rich Bradshaw
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?