0

ETA: not duplicate as I wasn't aware of what async was, so I didn't even know what to look for.

I'm having an issue saving location data to a variable. It seems the order of operations is not happening the way I'd expect it to. Any pointers?

Here's my code.

var test = 0;

$(document).ready(function() {
  //Get location
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      $("#location").html("latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude);
      test = position.coords.longitude;
      console.log(test + "a");
      return test;
    });
    console.log(test + "g");
  }

  console.log(test);
});

Instead of my console log saying, [longitude]a, then [longitude]g, then [longitude]. As I would expect, reading from top down, it instead says this.

"0g"

0

"-118.36397819999999a"

What am I doing wrong?

Angie
  • 25
  • 5
  • 1
    `getCurrentPosition()` is asynchronous. Can't eat a pizza before it gets delivered – charlietfl Dec 18 '16 at 20:42
  • Geolocation.getCurrentPosition() is an async call. You pass a function to it which does not execute immediately but when data is returned, So the later lines of Console.log code run before the current position has been found. (This question is not a duplicate unless you understand getCurrentPosition() is an async method) – Visual Micro Dec 18 '16 at 20:44
  • @VisualMicro thanks. if this were an answer i would give it a checkmark. – Angie Dec 28 '16 at 19:02

0 Answers0