Teererai Marange
Teererai Marange

Reputation: 2132

PhoneGap: variable scope

I am trying to write a function that returns an object representing the position of the device: I have tried:

  function getDevicePosition () {
    var positionObject;
    if (isDeviceReady) {
        navigator.geolocation.getCurrentPosition(function (position) {

            positionObject = position;
            console.log('location updated');
            console.log(positionObject.coords.longitude);//1. works
        }, function (err) {
            console.log('Failed to get device position' + err);
            return null;
        });

    } else {
        warnUser();
        return null;
    }
    console.log(positionObject.coords.longitude);//2. doesnt work as positionObject is null.
    return positionObject;
}

Notice that I have added comments marking statement 1 and statement 2. If I initialized position object in statement 1. Why is it undefined in statement 2?

Upvotes: 0

Views: 362

Answers (2)

Sirko
Sirko

Reputation: 74076

The call to navigator.geolocation.getCurrentPosition() is asynchronous, so the execution of the rest of the function does not wait until it is finished.

So your function is at execution basically reduced to this:

function getDevicePosition () {
    var positionObject;
    if (isDeviceReady) {
        // trigger some asynch function ...
    } else {
        warnUser();
        return null;
    }
    console.log(positionObject.coords.longitude);
    return positionObject;
}

From this code it should be pretty obvious, that at the point, your code reaches the console.log() your positionObject is not set, thus resulting in the error.

EDIT

With respect to your comment. The general design principle for such tasks is as follows:

// original function (triggered by a button or whatever)
function trigger() {
  // do some calculations before

  // trigger the position-retrival
  navigator.geolocation.getCurrentPosition(function (position) {
    // get the position
    // ...

    // call the handling function
    doStuff( position );
  });
}

// the function to do stuff based on the position
function doStuff( position ) {
// ...
}

Upvotes: 1

James Allardice
James Allardice

Reputation: 166001

Because getCurrentPosition is an asynchronous method. The line marked as 2 will run before the callback function gets a chance to execute, so positionObject will still be undefined.

You need to move all code that depends on positionObject inside the callback to getCurrentPosition.

Upvotes: 1

Related Questions