Emad Emami - 1 year ago 207
Javascript Question

# Return value from getCurrentPosition in Cordova

I'm trying to return the position value from the

navigator.geolocation.getCurrentPosition
function.

In this Cordova doc
navigator.geolocation.getCurrentPosition
uses the
onSuccess
and
onError
functions to get the position but I need something like this:

var onSuccess = function(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');
};
// onError Callback receives a PositionError object
function onError(error) {
alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}


And what I want is:

var p = navigator.geolocation.getCurrentPosition(onSuccess, onError);


How should I return the value from
navigator.geolocation.getCurrentPosition
to p?

What you want and what you can have are two different things. Almost everything in Cordova/Phonegap is asynchronous, which means you cannot do var p = navigator.geolocation.getCurrentPosition(onSuccess, onError);. You have to use the onSuccess function to return the value.
If there is no error and you are in onSuccess, this is where your code continues, and will use the position returned. Which means you probably have to refactor your code and/or rethink your workflow.