我在我的ionic应用程序中设置了地理位置,我想获得用户的当前位置并在应用程序上显示,但我收到了以下错误。
InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number
这是我的家.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 resp时,我得到坐标,但控制台日志this.lat和this.long返回undefined。
您应该在获得位置并完成后创建地图,但调用顺序有问题。这是一个异步执行,因此您必须确保initMap
在收到位置后即为。
您可以在currentPositon
函数的回调部分移动initMap
。
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);
});
}
}