0

Very simple question: Why does the following code return undefined values? function

GetLocation(location) {
    Lat = location.coords.latitude;
    Lon = location.coords.longitude;
    gCoords = "gCoords: " + Lat + "," + Lon;
    gLat = Lat;
    gLon = Lon;
    $timeout(function() {
      calculate();
    });
    return [gCoords, gLat, gLon];
  }
  var GPSInfo = navigator.geolocation.watchPosition(GetLocation);
  var info1 = GPSInfo[0]
  var info2 = GPSInfo[1]
  var info3 = GPSInfo[2]
  console.log(
    "gCoords: " + info1 +
    "   gLat: " + info2 + 
    "   gLon: " + info3   )

The console logs this: gCoords: undefined gLat: undefined gLon: undefined

Does anyone have any ideas on this?
Thank's in advanced!!!

Ian Pennebaker
  • 233
  • 4
  • 15
  • It's an asynchronous API. The "GetLocation" function will be called when the browser decides to call it, but that'll be after the code following the setup is done. It generally makes no sense to return values from asynchronous callback functions. Put your `console.log()` call **inside** the "GetLocation" function. – Pointy Aug 20 '14 at 14:51
  • @Pointy I'm assigning `info2` and `info3` to different variables after the log, so I need the `console.log()` outside `getLocation()` and I need to return the array still. – Ian Pennebaker Aug 20 '14 at 14:57
  • Well that's simply not possible when you're dealing with an asynchronous system. You have no choice but to structure your own code around the way the API works. That's life in the JavaScript world. – Pointy Aug 20 '14 at 14:59

0 Answers0