GetLocation(address: string) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
this.lat = results[0].geometry.location.lat();
this.lng = results[0].geometry.location.lng(); <== this.lat value is undefined
}
else {
alert("Something went wrong : " + status);
}
});
}
在这里,我无法在地址解析功能内分配组件级别变量“ lat”和“ lng”的值。 仅供参考:结果对象的位置对象中有值,但分配值后仍不确定,我不知道为什么?
答案 0 :(得分:-1)
import { Component, OnInit, NgZone } from '@angular/core'; <= 1. I have to import NgZone
constructor(private ngZone: NgZone) { } <= 2. declared it here
ngOnInit() { }
GetLocation(address: string) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, (results, status) => this.ngZone.run(() => { <= 3. and used it here
if (status == google.maps.GeocoderStatus.OK) {
this.lat = results[0].geometry.location.lat();
this.lng = results[0].geometry.location.lng();
}
else {
alert("Something went wrong : " + status);
}
}));
}
我找到了解决方案。我必须从'@ angular / core'导入NgZone 并在回调函数中使用了this.ngZone.run()函数(如第3条提示所示)。