0

I'm used to c-style programming, I cannot come up with how can I extract values from getCurrentPosition (function?).

For the case of this code,

navigator.geolocation.getCurrentPosition(function(pos) {
  var latitude = pos.coords.latitude;
  var longitude = pos.coords.longitude;
  document.write("Current pos : " + latitude + ", "+ longitude);
});

I'd like to change it to c-like code :

var a, b;
navigator.geolocation.getCurrentPosition(function(pos) {
  var latitude = pos.coords.latitude;
  var longitude = pos.coords.longitude;
  a = latitude;
  b = longitude;
  document.write("Current pos : " + latitude + ", "+ longitude);
});
document.write("Result " + a + " , " + b);

Is there any way to do this?

Phil
  • 157,677
  • 23
  • 242
  • 245
Wooni
  • 481
  • 1
  • 3
  • 17

1 Answers1

-1

Javascript is asynchrone, so you have to call

document.write("Result " + a + " , " + b)

inside the callback, try this:

<body>
  <script>
  var a, b;
  navigator.geolocation.getCurrentPosition(function(pos) {
  var latitude = pos.coords.latitude;
  var longitude = pos.coords.longitude;
  a = latitude;
  b = longitude;
  document.write("Current pos : " + latitude + ", "+ longitude);
  document.write("Result " + a + " , " + b);
});


  </script>
</body>
1pulsif
  • 471
  • 4
  • 14