Teererai Marange
Teererai Marange

Reputation: 2132

phoneGap: getDevicePosition

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

perhaps I should rephrase my question. 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: 35

Answers (1)

Marko
Marko

Reputation: 72222

Judging by the android tag I'm presuming you're testing on an Android device.

If that's the case, you need to add the right permissions in the AndroidManifest.xml file.

Specifially

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />

Read more here.

Upvotes: 1

Related Questions