无法在地理编码函数内分配组件变量值
Cannot assign component variable value inside geocode function
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' 的值。
仅供参考:其中结果的位置对象中有值,但在分配该值后它仍然未定义我不知道为什么?
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.hint.
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' 的值。 仅供参考:其中结果的位置对象中有值,但在分配该值后它仍然未定义我不知道为什么?
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.hint.