2
votes

I'm writing a Cordova/Phonegap app and I want to use Geolocation plugin to obtain longitude and latitude. This is my code:

$scope.showCoord = function() {
        var onSuccess = function(position) {
            console.log("Latitude: "+position.coords.latitude);
            console.log("Longitude: "+position.coords.longitude);
        };

        function onError(error) {
            console.log("Code: "+error.code);
            console.log("Message: "+error.message);
        };

        navigator.geolocation.getCurrentPosition(onSuccess, onError, { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true });
    }

When I try this plugin with the GPS it works very well but when I try it without GPS I receive timeout...I change the timeout to 100000 but doesn't work. Furthermore in my config.xml I added this code:

<feature name="Geolocation">
        <param name="android-package" value="org.apache.cordova.GeoBroker" />
    </feature>

How can I fix it?

1

1 Answers

7
votes

Update: Based on your comment below I've rewritten my answer

When you set enableHighAccuracy: true, the app is saying to the OS "give me a high accuracy position from the GPS hardware". If GPS is enabled in the OS settings, the GPS hardware is available, so requesting a high accuracy position will cause the OS to engage the GPS hardware to retrieve a high accuracy position. However, if GPS is disabled in the OS settings, then the high accuracy position that your app requested cannot be supplied by the OS, hence the error callback.

If you set enableHighAccuracy: false, the app is saying to the OS "give me a location of any accuracy", so the OS will return a location using cell triangulation/Wifi (or GPS if it is currently activated by another app).

So to cater for both high and low accuracy positions, you could first try for a high accuracy one, and if that fails, then request a low accuracy one. For example:

var maxAge = 3000, timeout = 5000;

var onSuccess = function(position) {
    console.log("Latitude: "+position.coords.latitude);
    console.log("Longitude: "+position.coords.longitude);
};

function onError(error) {
    console.log("Code: "+error.code);
    console.log("Message: "+error.message);
};

navigator.geolocation.getCurrentPosition(onSuccess, function(error) {
    console.log("Failed to retrieve high accuracy position - trying to retrieve low accuracy");
    navigator.geolocation.getCurrentPosition(onSuccess, onError, { maximumAge: maxAge, timeout: timeout, enableHighAccuracy: false });
}, { maximumAge: maxAge, timeout: timeout, enableHighAccuracy: true });