0

For some reason my "initialLocation" variable is undefined when I make an alert on it, even though I explicitly assign it in the callback function for getCurrentPosition. Variable "initialLocation" is declared globally btw.

Maybe I'm not understanding this concept of closures?

var initialLocation;

if (navigator.geolocation) {
    geoLocationError = true;
    navigator.geolocation.getCurrentPosition(function(position) {
        initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        getFood();
        }, geoError);
    alert(initialLocation);
} else {
    geoLocationError = false;
    noGeolocation(geoLocationError);
}
Vlad DX
  • 4,200
  • 19
  • 28
  • can you copy and paste the error in your question? –  Oct 25 '15 at 00:46
  • 5
    Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – JJJ Oct 25 '15 at 00:46
  • 2
    geolocation is asynchronous....you are trying to alert the value before it has been returned from location service – charlietfl Oct 25 '15 at 00:54
  • 1
    Also, [use `var`](https://stackoverflow.com/questions/1470488/what-is-the-function-of-the-var-keyword-and-when-to-use-it-or-omit-it). – Félix Saparelli Oct 25 '15 at 00:54
  • 1
    Place the `alert` inside `getCurrentPosition` – David Tansey Oct 25 '15 at 01:52

1 Answers1

1

navigator.geolocation.getCurrentPosition is asynchronous, so your alert is firing before initialLocation is set. You should place your alert inside the callback, just after you set initialLocation.

whitfin
  • 4,539
  • 6
  • 39
  • 67