我在离子应用程序中具有地理位置设置,我想获取用户的当前位置并在应用程序上显示,但出现以下错误。
InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number
这是我的home.ts代码
import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController, Platform, LoadingController } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
declare var google: any;
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public lat:number;
public long: number;
@ViewChild('map') mapElement: ElementRef;
map: any;
constructor(public navCtrl: NavController, public
platform: Platform, public geo: Geolocation, public loadingCtrl: LoadingController) {
platform.ready().then(() => {
this.currentPositon();
this.initMap();
});
}
initMap() {
let loading = this.loadingCtrl.create({
content:'Locating...'
});
loading.present();
this.map = new google.maps.Map(this.mapElement.nativeElement, {
zoom: 18,
mapTypeId:google.maps.MapTypeId.ROADMAP,
center: {lat: this.lat, lng: this.long},
});
loading.dismiss();
}
currentPositon()
{
this.geo.getCurrentPosition().then((resp) => {
this.lat = resp.coords.latitude;
this.long = resp.coords.longitude
console.log(resp);
}).catch((error) => {
console.log('Error getting location', error);
});
}
}
我在做什么错?当我console.log响应时,我得到坐标,但控制台记录this.lat和this.long返回未定义。
答案 0 :(得分:1)
一旦获得位置并完成操作,就应该创建地图,但是呼叫顺序存在问题。它是异步执行的,因此您必须确保initMap
在收到职位之后就可以使用。
您可以在initMap
函数的回调部分中移动currentPositon
。
import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController, Platform, LoadingController } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
declare var google: any;
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public lat:number;
public long: number;
@ViewChild('map') mapElement: ElementRef;
map: any;
constructor(public navCtrl: NavController, public
platform: Platform, public geo: Geolocation, public loadingCtrl: LoadingController) {
platform.ready().then(() => {
this.currentPositon();
// this.initMap(); <-- do not call here
});
}
initMap() {
let loading = this.loadingCtrl.create({
content:'Locating...'
});
loading.present();
this.map = new google.maps.Map(this.mapElement.nativeElement, {
zoom: 18,
mapTypeId:google.maps.MapTypeId.ROADMAP,
center: {lat: this.lat, lng: this.long},
});
loading.dismiss();
}
currentPositon()
{
this.geo.getCurrentPosition().then((resp) => {
this.lat = resp.coords.latitude;
this.long = resp.coords.longitude;
this.initMap(); //<-- init map once the position is received
console.log(resp);
}).catch((error) => {
console.log('Error getting location', error);
});
}
}