0

I'm starting to learn javascript and was fiddling around gps. Currently, I'm having issues with scoping on a function.

The code

$(document).ready(function () {
    var lat, lng;

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            $(document).data('lat', position.coords.latitude); //undefined outside
            lat = position.coords.latitude; //undefined outside
            lng = position.coords.longitude; //undefined outside
        });
    }

    var coords = new google.maps.LatLng(lat,lng); //lat & lng are undefined
});

the problem lies in the fact that whatever value I assign in the local scope of the function called by getCurrentPosition is not kept. What is best practice on handling this issue. I'm assuming it is to just return an object back containing the data, but how exactly do i do that? I tried doing that, but it still wasn't working

Cœur
  • 37,241
  • 25
  • 195
  • 267
theStig
  • 612
  • 1
  • 13
  • 33
  • 8
    It isn't a scope problem, it is a timing problem. The problem is that the coordinates are not set until after the "coords" variable is created (the geolocation is asynchronous) – geocodezip Aug 25 '13 at 19:24
  • 3
    Have a look at http://stackoverflow.com/q/14220321/218196 to understand the problem (even thought it's about Ajax, it applies to all asynchronous situations). – Felix Kling Aug 25 '13 at 19:32

1 Answers1

3

Well, I figured it out thanks to the two comments above. The problem isn't a scoping problem, but rather an asynchronous problem. Refer to stackoverflow.com/q/14220321/218196

$(document).ready(function () {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, error, { maximumAge: 75000 });
    }

    function success(position) {
        var coords = new google.maps.LatLng(
            position.coords.latitude,
            position.coords.longitude);
        initMap(coords);
    }

    function error(err) {
        //coordinates of LA
        initMap(new google.maps.LatLng(34,118));
    }


    function initMap(coords) {
       //logic here 
    }
});
theStig
  • 612
  • 1
  • 13
  • 33