2019年11月14日 星期四

[morse]使用 Ionic Native 插件在 Ionic 4應用程序中打開設備 GPS,而無需離開應用程序

建立 ionic 專案  ionic start ionicGPS blank

選擇 Angular

切換到專案目錄  cd ionicGPS




在這裡,我們將創建一個新的Ionic 4應用程序,該應用程序將包含三個插件,這些插件將有助於提供用戶更加友好的行為。


cordova-plugin-android-permissions:
通過顯示權限對話框來獲取權限。我們將使用此插件來獲取 Geolocation 訪問權限,但這可用於任何類型的權限。
$ ionic cordova plugin add cordova-plugin-android-permissions
$ npm install @ionic-native/android-permissions



cordova-plugin-request-location-accuracy:
向用戶顯示一個對話框,以打開我們在下圖中顯示的 GPS,這樣用戶無需離開應用程序或進行設置。
$ ionic cordova plugin add cordova-plugin-request-location-accuracy
$ npm install @ionic-native/location-accuracy



cordova-plugin-geolocation:
最後,在獲得位置訪問權限並打開設備GPS之後,我們將使用此Geolocation插件獲取準確的設備Geolocation坐標。
$ ionic cordova plugin add cordova-plugin-geolocation
$ npm install @ionic-native/geolocation



接下來,我們需要將這些插件注入app.module.ts文件中,然後添加到 provider 數組中

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
 
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
 
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
 
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { LocationAccuracy } from '@ionic-native/location-accuracy/ngx';
 
 
@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    AndroidPermissions,
    Geolocation,
    LocationAccuracy,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}



現在,我們將在應用程序的home組件中使用它們。在home.component.ts文件中,我們將添加以下方法。

通過調用以下方法checkGPSPermission()檢查應用程序是否具有訪問設備位置的權限

//Check if application having GPS access permission  
checkGPSPermission() {
 this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION).then(
   result => {
  if (result.hasPermission) {

    //If having permission show 'Turn On GPS' dialogue
    this.askToTurnOnGPS();
  } else {

    //If not having permission ask for permission
    this.requestGPSPermission();
  }
   },
   err => {
  alert(err);
   }
 );
}



如果沒有,那麼我們將調用requestGPSPermission()方法來從用戶那裡即時獲取位置許可。

  requestGPSPermission() {
    this.locationAccuracy.canRequest().then((canRequest: boolean) => {
      if (canRequest) {
        console.log("4");
      } else {
        //Show 'GPS Permission Request' dialogue
        this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION)
          .then(
            () => {
              // call method to turn on GPS
              this.askToTurnOnGPS();
            },
            error => {
              //Show alert if user click on 'No Thanks'
              alert('requestPermission Error requesting location permissions ' + error)
            }
          );
      }
    });
  }



如果應用程序具有位置訪問權限,則我們將調用askToTurnOnGPS()方法。這是我們在這裡使用的方法😛此GPS顯示應用程序中的開啟對話

  askToTurnOnGPS() {
    this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(
      () => {
        // When GPS Turned ON call method to get Accurate location coordinates
        this.getLocationCoordinates()
      },
      error => alert('Error requesting location permissions ' + JSON.stringify(error))
    );
  }



用戶成功打開GPS後,我們將調用getLocationCoordinates()方法來獲取設備的準確位置。

  // Methos to get device accurate coordinates using device GPS
  getLocationCoordinates() {
    this.geolocation.getCurrentPosition().then((resp) => {
      this.locationCoords.latitude = resp.coords.latitude;
      this.locationCoords.longitude = resp.coords.longitude;
      this.locationCoords.accuracy = resp.coords.accuracy;
      this.locationCoords.timestamp = resp.timestamp;
    }).catch((error) => {
      alert('Error getting location' + error);
    });
  }



添加上述方法後,我們完整的Home Component ts文件將如下所示:

import { Component } from '@angular/core';
 
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { LocationAccuracy } from '@ionic-native/location-accuracy/ngx';
 
 
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss']
})
export class HomePage {
 
  locationCoords: any;
  timetest: any;
 
  constructor(
    private androidPermissions: AndroidPermissions,
    private geolocation: Geolocation,
    private locationAccuracy: LocationAccuracy
  ) {
    this.locationCoords = {
      latitude: "",
      longitude: "",
      accuracy: "",
      timestamp: ""
    }
    this.timetest = Date.now();
  }
 
 
  //Check if application having GPS access permission  
  checkGPSPermission() {
    this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION).then(
      result => {
        if (result.hasPermission) {
 
          //If having permission show 'Turn On GPS' dialogue
          this.askToTurnOnGPS();
        } else {
 
          //If not having permission ask for permission
          this.requestGPSPermission();
        }
      },
      err => {
        alert(err);
      }
    );
  }
 
  requestGPSPermission() {
    this.locationAccuracy.canRequest().then((canRequest: boolean) => {
      if (canRequest) {
        console.log("4");
      } else {
        //Show 'GPS Permission Request' dialogue
        this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION)
          .then(
            () => {
              // call method to turn on GPS
              this.askToTurnOnGPS();
            },
            error => {
              //Show alert if user click on 'No Thanks'
              alert('requestPermission Error requesting location permissions ' + error)
            }
          );
      }
    });
  }
 
  askToTurnOnGPS() {
    this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(
      () => {
        // When GPS Turned ON call method to get Accurate location coordinates
        this.getLocationCoordinates()
      },
      error => alert('Error requesting location permissions ' + JSON.stringify(error))
    );
  }
 
  // Methos to get device accurate coordinates using device GPS
  getLocationCoordinates() {
    this.geolocation.getCurrentPosition().then((resp) => {
      this.locationCoords.latitude = resp.coords.latitude;
      this.locationCoords.longitude = resp.coords.longitude;
      this.locationCoords.accuracy = resp.coords.accuracy;
      this.locationCoords.timestamp = resp.timestamp;
    }).catch((error) => {
      alert('Error getting location' + error);
    });
  } 
}
 



在Home組件的HTML模板中,我們只有一個按鈕,該按鈕將調用checkGPSPermission方法,該方法已添加到上面的ts文件中,並且還顯示了收到的地理位置坐標。

< ion-grid fixed>
  < ion-row>
    < ion-col text-center>
      < ion-button (click)="checkGPSPermission()">
        Request GPS Accuracy
      < /ion-button>
    < /ion-col>
  < /ion-row>
  < ion-row>
    < ion-col size="4">Longitude< /ion-col>
    < ion-col> {{locationCoords.longitude}}< /ion-col>
  < /ion-row>
  < ion-row>
    < ion-col size="4">Latitude< /ion-col>
    < ion-col>{{locationCoords.latitude}}< /ion-col>
  < /ion-row>
  < ion-row>
    < ion-col size="4">Accuracy< /ion-col>
    < ion-col>{{locationCoords.accuracy}}< /ion-col>
  < /ion-row>
  < ion-row>
    < ion-col size="4">Timestamp< /ion-col>
    < ion-col>{{locationCoords.timestamp | date:'medium'}}< /ion-col>
  < /ion-row>
< /ion-grid> 


修改 index.html

  
< !doctype html>
< html lang="en">

< head>
  < meta charset="utf-8" />
  < title>ionic app< /title>

  < base href="./" />

  < meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  < meta name="format-detection" content="telephone=no" />
  < meta name="msapplication-tap-highlight" content="no" />

  < link rel="icon" type="image/png" href="assets/icon/favicon.png" />

  < !-- add to homescreen for ios -->
  < meta name="apple-mobile-web-app-capable" content="yes" />
  < meta name="apple-mobile-web-app-status-bar-style" content="black" />

  < script type="text/javascript" src="cordova.js">< /script>

< /head>

< body>
  < app-root>< /app-root>
< /body>

< /html>
  



就是這樣,在上面的教程中,我們了解瞭如何在為應用程序提供地理定位權限後打開設備GPS來更準確地獲取用戶設備的地理定位權限。





以下是 Android 及 IOS 的發佈建置參考指令:
創建 Android 應用

使用ionic tool 創建,測試,運行你的apps

$ cd myApp
$ ionic cordova platform add android
$ ionic cordova build android
$ ionic cordova emulate android



創建IOS應用

$ cd myApp
$ ionic cordova platform add ios
$ ionic build ios
$ ionic emulate ios

如果出現"ios-sim was not found."錯誤,可以執行以下命令:
npm install -g ios-sim




創建電腦應用

在電腦執行出現異常,提示: cordova_not_available

解法是新增一平台為browser

ionic cordova platform add browser

再以下列指令取代ionic serve即可


ionic cordova run browser





沒有留言:

張貼留言