WeSt
WeSt

Reputation: 2684

Ionic - navigator.geolocation returns empty error object

I am building a small app that relies on geolocation. I use the following code to get the current location from the device:

var options = { maximumAge: 3000, timeout: 300000, enableHighAccuracy: true };
navigator.geolocation.watchPosition(function(result) {
  console.info(result);
}, function(error) {
  console.error(JSON.stringify(error));
}, options);

However, this always call the error callback with an empty error object:

1     123317   error    {}

There is no code nor message, just an empty object. Also interesting is that the error callback is called immediately, no matter what I set as timeout.

My AndroidManifest.xml looks like this:

<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" />

The result is the same weather I run it in the emulator or directly on my phone. If anyone has any idea on how to fix this, hints would be greatly appreciated.

Upvotes: 1

Views: 1628

Answers (3)

Simp Coder
Simp Coder

Reputation: 11

Try this below code for checking error It might be related to the insecure origin means it will not work for the private IP's

https://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features/

navigator.geolocation.getCurrentPosition(
    function(position) {
        console.log(position);
    },
    function(error) {
        console.log(error.code + " " + error.message);
    }
);

Upvotes: 0

Agney
Agney

Reputation: 19224

This is because the error object returned is a special object. Using JSON.stringify does not consider inherited properties. This is especially true if you are using Chrome or Safari.

$cordovaGeolocation
.getCurrentPosition()
.then((resp)=>{
  $scope.lat = resp.coords.latitude;
  $scope.lon = resp.coords.longitude;
}).catch((error)=> {
  $scope.errm = error.message;
  $scope.errc = error.code;
  console.log(error.code+" "+error.message)
});

You can use this code to view the error code and message. If you want to view complete object you can use SO Answer to do so.

As of the errors, there are several ones like need for secure origins or a wifi connection that might be limiting the same.

PS: This holds true for the Geolocation object also.

Upvotes: 4

Anuj
Anuj

Reputation: 650

Use following code

var options = { enableHighAccuracy: true, timeout:5000, maximumAge: 0 };

Upvotes: -1

Related Questions