Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic display error if gps is turned off

Got a bit of an issue trying to determine if someone has their GPS turned off in Ionic/Cordova.

Here is what I am trying to do at the moment, this works in the browser fine but not on android.

navigator.geolocation.getCurrentPosition(function(pos) {}, function(err) {
    alert('We were unable to determine your location, please turn on your GPS/Location services');
});

Another thing is does anyone know if its possible to give a prompt to turn on GPS with Ionic/cordova?

Anyone got any ideas?

like image 421
Jack Avatar asked Oct 27 '15 16:10

Jack


3 Answers

Please add this plugin,

cordova plugin add cordova.plugins.diagnostic

1.Determine if someone has their GPS turned off in Ionic/Cordova

Contoller

if (window.cordova) {
    cordova.plugins.diagnostic.isLocationEnabled(function(enabled) {
        alert("Location is " + (enabled ? "enabled" : "disabled"));
    }, function(error) {
        alert("The following error occurred: " + error);
    });
}

2.Giving a prompt to turn on GPS

Controller

if (window.cordova) {
    cordova.plugins.diagnostic.switchToLocationSettings();
}
like image 108
Muhsin Keloth Avatar answered Oct 24 '22 11:10

Muhsin Keloth


I think it is easier when using ngCordova plugin to detect GPS status. You can try this two plugins:

  1. $cordovaGeolocation:
    • This plugin using Wifi/3G/GPS to detect current position.
    • It also has watch function and error callback. You should use that for checking.
  2. Or $cordovaBackgroundGeolocation:
    • This works same as $cordovaGeolocation but has battery-saving feature.
  3. For prompt message, I think the only way is do it through plugin written by Java code. Check out Introduction to custom Cordova plugin development for more details.
like image 33
Nam Pham Avatar answered Oct 24 '22 09:10

Nam Pham


Try with this

let optionsGPS = {timeout: 4000, enableHighAccuracy: true};
Geolocation.getCurrentPosition(optionsGPS).then((result) => {
  this.loadMap(result.coords.latitude, result.coords.longitude);
}).catch((err) => {
  let alert = this.alertCtrl.create({
        title: 'Error on GPS',
        subTitle: 'You need active the GPS',
        buttons: ['Ok']
    });
    alert.present();
});

I had the same problem, and this it worked for me

like image 21
CrsCaballero Avatar answered Oct 24 '22 10:10

CrsCaballero