【发布时间】:2020-05-03 10:02:56
【问题描述】:
您好,我正在尝试获取 ionic-4 中的纬度和经度值。我的问题是,当我最初尝试获取 lat 和 long 值时,它会抛出错误应用程序没有足够的地理位置权限。但是,在用户允许访问位置后,当我刷新屏幕时,我可以获得 lat 和 long 值。以下是我尝试过的代码。
关注此文档: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);
});
}
}
- 并在
app.component.ts组件的构造函数中调用location service。下面是代码
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);
}
}
这里的问题是,位置服务在用户允许位置之前触发。当我刷新屏幕时,现在用户已经允许该位置。所以我可以得到值。
请让我知道解决此问题的可能方法。提前致谢,我们将提供解决方案。
【问题讨论】:
标签: angular ionic3 ionic4 angular8