angularcordovaionic-frameworkgeolocationionic3

Ionic 3 - check if location is enabled


I am trying to do a few things in one. The first thing I am trying to do is get the device location. On Android, it prompts to grant the app permission to access location, which is all good. I am trying to check if the device has the location turn on and if no, I will like to prompt the user to do so using switchToLocationSettings(). The issue I am having is when I added the code below doesn't run from the line this._DIAGNOSTIC.isLocationEnabled().then((isEnabled) => { I press the button over and over and nothing. Please how do prompt the user to turn on device location and then navigate using switchToLocationSettings() and when it is turn on, I can get the user location and return it. Thanks

html

<ion-item>
    <ion-label color="primary" stacked>Enter your zip code</ion-label>
    <button item-right ion-button (click)="getGeolocation()" ion-button clear color="dark" type="button" item-right large>
        <ion-icon color="dark" name="locate" md="md-locate" color="primary"></ion-icon>
    </button>
 </ion-item>

ts

import { Component } from '@angular/core';
import { NavController, Platform, LoadingController, AlertController } from 'ionic-angular';
import { Geolocation, Geoposition, GeolocationOptions }  from '@ionic-native/geolocation';
import { Diagnostic } from '@ionic-native/diagnostic';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  geolocationOptions: GeolocationOptions;
  loading             : any;
  location            : Object;

  constructor(
    private alertCtrl : AlertController,
    private _DIAGNOSTIC: Diagnostic,
    private _GEO : Geolocation,
    private loadingCtrl: LoadingController,
    public navCtrl: NavController,
    private _PLATFORM : Platform,
    public restProvider: RestProvider
  ) {
  }
  
   async getDeviceCurrentPosition() {
    await this._PLATFORM.ready();
    this.geolocationOptions = {
      enableHighAccuracy: true
    }
    await this._GEO.getCurrentPosition(this.geolocationOptions).then((loc : any) =>
    {
      console.log("getting position");
      //check if location is turn on
      this.loading = this.loadingCtrl.create({
        spinner: 'crescent',
        content: 'Loading Please Wait...',
      });
      this.loading.present();
        this._DIAGNOSTIC.isLocationEnabled().then((isEnabled) => {
          if(!isEnabled && (this._PLATFORM.is('android') || this._PLATFORM.is('ios'))){
            let confirm = this.alertCtrl.create({
              title: '<b>Location</b>',
              message: "For best results, turn on devices location.",
              buttons: [
                {
                  text: 'cancel',
                  role: 'Cancel',
                  handler: () => {
                    this.closeLoader();
                  }
                },
                {
                  text: 'Ok',
                  handler: () => {
                    this._DIAGNOSTIC.switchToLocationSettings();
                  }
                }
              ]
            });
            confirm.present();
            }
        })
        .catch((error : any) => 
        {
          this.closeLoader();
          console.log('Location Not enabled', error);
        });
    
      })
      .catch((error : any) =>
      {
        console.log('Error getting location', error);
      });
  }


  private closeLoader(){
    this.loading.dismiss();
  }
}

Solution

  • You should check if the location is enabled first and then get the current position. You are doing it in a reverse way. The getCurrentPosition method returns a Promise that resolves with the position of the device. If the location is not enabled it does not return any Promise. So the code will be,

    this._DIAGNOSTIC.isLocationEnabled().then((isEnabled) => {
      if(!isEnabled && this._PLATFORM.is('cordova')){
          //handle confirmation window code here and then call switchToLocationSettings
        this._DIAGNOSTIC.switchToLocationSettings();
      }
      else{
          this._GEO.getCurrentPosition(this.geolocationOptions).then((loc : any) =>
           {
               //Your logic here
           }
          )
      }
    })