0

How do I data is returned for an array and not for the functions onSuccess and onError?

function onSuccess(position) {
    alert('Latitude: '          + position.coords.latitude          + '\n' +
          'Longitude: '         + position.coords.longitude         + '\n' +
          'Altitude: '          + position.coords.altitude          + '\n' +
          'Accuracy: '          + position.coords.accuracy          + '\n' +
          'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
          'Heading: '           + position.coords.heading           + '\n' +
          'Speed: '             + position.coords.speed             + '\n' +
          'Timestamp: '         + position.timestamp                + '\n');
}
function onError(error) {
    alert('code: '    + error.code    + '\n' +
          'message: ' + error.message + '\n');
}
navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 });

Example of what I need:

geolocation = navigator.geolocation.watchPosition(null, null, { timeout: 30000 });
if(!geolocation.error)
      alert(geolocation.coords.latitude);

Plugin: https://github.com/apache/cordova-plugin-geolocation

Alisson Linneker
  • 312
  • 2
  • 12
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – VLAZ Aug 31 '16 at 22:19
  • I found no example for my case. Could you explain me? – Alisson Linneker Aug 31 '16 at 22:27
  • there is no example. It is explaining that javascript does not work in the way you are asking. you need to come at it from an async mind set. – adrianj98 Aug 31 '16 at 22:33

1 Answers1

0

I guess from your question that you would like your code to execute linearly. But it cannot. The block of code is executed, then, eventually, the location arrives and the callback is called. But it happens at a different time (even a few ms count) and in a different stack trace. This is how asynchronous Javascript works.

If you're not familiar with the concept, you should go read some articles on the subject. For your reference, I've translated your code into Promise code, which is one of the best technique available to help with asynchronicity.

new Promise(function(resolve, reject) {
  navigator.geolocation.watchPosition(resolve, reject, { timeout: 30000 });
})
.then(function(location) {
  console.log(location.coords.latitude);
})
.catch(function (error) {
  console.log('code: '    + error.code    + '\n' +
        'message: ' + error.message + '\n');
});

BTW, do yourself a favor and use console.log. alert() is so 2000's! :)

solendil
  • 8,152
  • 3
  • 27
  • 29