我在Angular app中使用反向地理编码。
所需的脚本添加到index.html中
<script async defer src="https://maps.googleapis.com/maps/api/js">
</scrip>
并且组件文件看起来像这样
import { Component } from '@angular/core';
declare const google: any;
export class MapComponent {
lat;
lng;
address;
constructor() {
this.locate();
}
public locate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
position => {
this.lat = position.coords.latitude; // Works fine
this.lng = position.coords.longitude; // Works fine
let geocoder = new google.maps.Geocoder();
let latlng = new google.maps.LatLng(this.lat, this.lng);
let request = {
latLng: latlng
};
geocoder.geocode(request, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0] != null) {
this.address = results[0].formatted_address; //<<<=== DOES NOT WORK, when I output this {{ address }} in the html, it's empty
console.log(this.address); //<<<=== BUT here it Prints the correct value to the console !!!
} else {
alert("No address available");
}
}
});
},
error => {
console.log("Error code: " + error.code + "<br /> Error message: " + error.message);
}
);
}
}
}
在组件html文件中,它应该输出地址
<div>{{ lat }}</div> // Works fine
<div>{{ lng }}</div> // Works fine
<div>{{ address }}</div> // Deosn't Work, EMPTY
但它总是空的,不过这一行
console.log(this.address);
打印出正确的值。
我在这里看到两种可能性,但没有复制就无法确认,所以我会列出它们。
更改变量以进行显示的代码未在Angular的区域内执行。当你在这里使用来自第三方库的回调时,往往会发生这种情况。
要修复,请注入NgZone
并使用this.ngZone.run
包装您想要在UI中反映的任何更改,如下面的代码段所示。
constructor(private ngZone: NgZone) {}
locate() {
/* ... */
this.ngZone.run(() => {
this.location = results[0].formatted_address
})
/* ... */
}
this
在某个地方,你已经失去了指向类实例的this
,而你却将结果写入其他东西。你console.log
工作,因为它也记录错误的this
,而Angular没有显示任何东西,因为实际属性没有改变。
当您设置this.location
时,您的组件可能尚未初始化,因为Angular无法控制何时调用构造函数。
您应该尝试在locate
中放置ngOnInit
调用,以确保您的组件已准备好显示数据绑定属性:
ngOnInit() {
this.locate();
}