嗨,我想在ionic-4中获取纬度和经度值。我的问题是,当我尝试获取纬度和经度值时,它抛出了错误信息 应用程序没有足够的地理定位权限。. 但是,当用户允许访问位置后,当我刷新屏幕时,我可以得到经纬度的值。下面是我尝试的代码。
按照这个文档。ionic geolocaiton document
我用的是 @ionic-native/geolocation/ngx
我创造了 service
有名字 location.service.ts
以下是代码
import { Geolocation } from '@ionic-native/geolocation/ngx;
constructor(private geolocation: Geolocation) {
this.geolocation.getCurrentPosition({maximumAge: 1000, timeout: 5000,
enableHighAccuracy: true }).then((resp) => {
console.log("geo location values", resp);
this.servcurlat = resp.coords.latitude
this.servcurlong = resp.coords.longitude
console.log("lactionservice latlongs",this.servcurlat, this.servcurlong);
let watch = this.geolocation.watchPosition();
watch.subscribe((data) => {
this.goeData = data;
this.movelatlong = this.goeData.coords;
this.movelat = this.goeData.coords.latitude;
this.movelong = this.goeData.coords.longitude;
console.log("moving data" , this.goeData);
});
}).catch((error) => {
console.log('Error getting location', error);
});
}
}
location service
构造者中 app.component.ts
组件。以下是代码import { Component, ViewChild } from '@angular/core';
import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { LocationService } from './_services/location.service';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
curlat: any = '';
curlong: any = '';
constructor(
private router: Router,
private localnotifications: LocalNotifications,
private complaintservice: ComplaintregService,
private locationservice: LocationService,
) {
platform.ready().then(() => {
this.initializeApp(statusBar, splashScreen);
});
}
initializeApp(statusBar: StatusBar,
splashScreen: SplashScreen) {
this.curlat = this.locationservice.servcurlat;
this.curlong = this.locationservice.servcurlong
console.log("lat and long values: ",this.curlat,this.curlong);
}
}
这里的问题是,位置服务在用户允许该位置之前就已经启动了,当我刷新屏幕时,现在用户已经允许了该位置。因此,我可以得到的值。
请让我知道可能的方式摆脱这个问题。提前感谢和解决方案将被appriciated。
也许可以尝试在闪屏页面后获得权限,例如在你的登录页面。