Adam Wolf
Adam Wolf

Reputation: 309

making a cordova geolocation function to return position

I looked at examples on Cordova Geolocation and I am having trouble figuring out how to return the position from its function so I can call it several times from different locations.

Here is an example of getting the position:

    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');
    };

    function onError (error) {
        alert('code: ' + error.code + '\n' +
            'message: ' + error.message + '\n');
    }

    navigator.geolocation.getCurrentPosition(onSuccess, onError);

So I want to be able to call a function and have it return the position object, what its getting from 'onSuccess'

Upvotes: 0

Views: 230

Answers (1)

Blauharley
Blauharley

Reputation: 4256

May be bind is what you are looking for:

var getPosition
function onSuccess(position){
  getPosition = function(position){
    // do somethin with the position object afterwards
  }.bind(null, position);
}

// ... some code or some timeout after onSuccess function has been fired

if(getPosition)getPosition();

Just to make it clear of how to the code above was supposed to work:

// simulate cordova-geolocation-onSuccess call
onSuccess({x:2,y:5});

setTimeout(function(){

   if(getPosition)getPosition();

},2000);

Hope this helps and I've understood your question correctly.

Note: bind can be used to make a function that can be executed within a certain context(first param) and with certain passed parameter values(second, third... param).

According to your comment below: You can also use a callback function as parameter to achieve this:

function getUserPosition(callback) {
  function onSuccess(position) {
    callback(position);
  };
  $cordovaGeolocation.getCurrentPosition(options).then(onSuccess);
};

getUserPosition(function(position){
  // do something with position object here
});

But when you want to use a function that can really return a geolocation-object you have to use the first answer.

Upvotes: 1

Related Questions