Search code examples
ionic-frameworkgeolocationcordova-plugins

Ionic 3 geolocation error


I am using the ionic native geolocation plugin

https://ionicframework.com/docs/native/geolocation/ to get users current position. Everything works fine apart from an issue I am experiencing when the user has his phones location turned off, then the app cannot turn it back on even if the user allows location access.

        this.options = {
            enableHighAccuracy: true,
            timeout: 10000
        };
        this.geolocation.getCurrentPosition(this.options).then((pos: Geoposition) => {
            this.currentLat = pos.coords.latitude;
            this.currentLon = pos.coords.longitude;

        );
        }, (err: PositionError) => {
            console.log("error : " + err.message);

        })

I can't seem to understand why this is happening.


Solution

  • If the user has his device location off then you need to check it using ionic native diagnostic plugin and if location is off take user to locationSettings

    this.diagnostic.isGpsLocationEnabled().then(state => {
      if (!state) {
        let confirm = this.alertCtrl.create({
          title: '<b>Location</b>',
          message: 'Location information is unavaliable on this device. Go to Settings to enable Location.',
          buttons: [
            {
              text: 'cancel',
              role: 'Cancel',
              handler: () => {
                this.navCtrl.push(alternatePage); // this is optional(you can use only one button if maps is necessary) according to your needs if you want to navigate user to some other place if he does not give location access.
              }
            },
            {
              text: 'Go to settings,
              handler: () => {
                this.diagnostic.switchToLocationSettings()
              }
            }
          ]
        });
        confirm.present();
      }
      else {
        this.navCtrl.push(yourMapsPage) // if access is available take to maps page. 
      }
    })