我的home.ts文件夹上有一个名为displayMap()
的函数。我想在其他函数上使用 pos 变量。
我尝试将其设置为全局变量,但有些问题,无法在途中执行此操作。
我定义了一个全局 Pos 变量,如以下代码所示。
export class HomePage {
globalPos: any;
并尝试使用以下代码将 pos 值保存到全局 Pos。
displayMap(){
let pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
let info = new google.maps.InfoWindow;
that.globalPos = pos;
}
displayMap() 函数。
displayMap() {
let that = this;
let latLng = new google.maps.LatLng(40.106334, 29.510615);
let mapOptions = {
center: latLng,
disableDefaultUI: true,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
let pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
let info = new google.maps.InfoWindow;
that.globalPos = pos;
info.setContent('you are here!');
info.setPosition(pos);
info.open(that.map);
that.map.setCenter(pos);
})
}
}
这里的情况是你没有使用箭头函数,所以在navigator.geolocation.getCurrentPosition()
里面,它将被阻止作用域为该函数,并且它无法访问全局作用域。
尝试更改该代码的代码:
navigator.geolocation.getCurrentPosition(position => {
// YOUR CODE...
this.globalPos = pos;
});
希望这有帮助。