使用 Angular 进行反向地理编码

Reverse geocoding using Angular

我在 Angular 应用程序中使用反向地理编码。

需要的脚本已添加到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);

打印出正确的值。

我在这里看到有两种可能性,但如果没有复制就无法确认,所以我将它们都列出来。

1) 你不在Angular的区域

更改显示变量的代码未在 Angular 的区域内执行。当像您在此处所做的那样使用来自第三方库的回调时,往往会发生这种情况。

要修复,请注入 NgZone 并将您希望在 UI 中看到的任何更改包装成 this.ngZone.run,如以下代码段所示。

constructor(private ngZone: NgZone) {}

locate() {
  /* ... */
      this.ngZone.run(() => {
        this.location = results[0].formatted_address
      })
  /* ... */
}

2) 错误this

在此过程中的某个地方,您丢失了指向 class 实例的 this,而是将结果写入其他内容。你 console.log 工作是因为它也记录了错误的 this,而 Angular 什么也没显示,因为 actual 属性 没有改变。

当您设置 this.location 时,您的组件可能尚未初始化,因为 Angular 无法控制 何时 将调用构造函数。

您应该尝试在 ngOnInit 中放置 locate 调用,以确保您的组件已准备好显示数据绑定属性:

ngOnInit() {
  this.locate();
}