使用Angular进行反向地理编码

6
我正在使用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);

打印出正确的值。


谢谢,你的代码帮我启动了我的地理编码器! - Henry
2个回答

3

我看到有两种可能性,但如果没有重现,我无法确认,因此我将列出它们。

1) 您不在Angular的区域内

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

要解决此问题,请注入NgZone并使用this.ngZone.run包装您想要在UI中看到反映的任何更改,如以下代码段所示。

constructor(private ngZone: NgZone) {}

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

2) 错误的this

在某个地方,您丢失了指向类实例的this,而是将结果写入其他位置。您的console.log之所以有效是因为它也记录了错误的this,而Angular未显示任何内容是因为实际属性没有更改。


你救了我的命 :) - M.J
@M.J,对我来说它显示了以下错误:ERROR ReferenceError: google is not defined - Anil

0

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

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

ngOnInit() {
  this.locate();
}

这里的正确答案是你不在Angular的区域内。 - yurzui
谢谢,我尝试在 ngOnInit 中调用它,但是没有成功,但是使用 ngZone 解决了这个问题。 - M.J

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接