我正在尝试将一些事情合而为一。我要做的第一件事是获取设备位置。在android上,它提示您授予应用访问位置的权限,这一切都很好。
我正在尝试检查设备是否打开了位置信息,如果没有打开,我想提示用户使用switchToLocationSettings()
。
我遇到的问题是,当我添加下面的代码时,不是从this._DIAGNOSTIC.isLocationEnabled().then((isEnabled) => {
行开始,我一遍又一遍地按了按钮,什么也没做。请如何提示用户打开设备位置,然后使用switchToLocationSettings()
进行导航,当它打开时,我可以获取用户位置并返回它。谢谢
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();
}
}
答案 0 :(得分:2)
您应该先检查该位置是否启用,然后再获取当前位置。您正在以相反的方式进行操作。 getCurrentPosition 方法返回一个 Promise ,该信息会根据设备的位置进行解析。如果未启用该位置,则不会返回任何Promise。 这样的代码将是
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
}
)
}
})