Variable scope in javascript

Posted by Rich Bradshaw on Stack Overflow See other posts from Stack Overflow or by Rich Bradshaw
Published on 2010-06-03T12:05:38Z Indexed on 2010/06/03 12:14 UTC
Read the original article Hit count: 229

Filed under:

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:

  1. Set lat and lon to 0
  2. 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?

© Stack Overflow or respective owner

Related posts about JavaScript