【问题标题】:Reverse geocoding using Angular使用 Angular 进行反向地理编码
【发布时间】:2018-05-30 21:47:40
【问题描述】:

我在 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);

打印出正确的值。

【问题讨论】:

  • 谢谢,您的代码帮助我启动了我的地理编码器!

标签: angular google-maps-api-3 geocoding reverse-geocoding


【解决方案1】:

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

1) 你不在 Angular 的范围内

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

要进行修复,请注入 NgZone 并使用 this.ngZone.run 包装您希望在 UI 中看到的任何更改,如下面的 sn-p 所示。

constructor(private ngZone: NgZone) {}

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

2) 错误this

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

【讨论】:

  • 你救了我的命 :)
  • @M.J,对我来说它显示如下错误ERROR ReferenceError: google is not defined
【解决方案2】:

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

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

ngOnInit() {
  this.locate();
}

【讨论】:

  • You're not in Angular's zone 是正确答案
  • 谢谢,我尝试拨打ngOnInit,但没有成功,但ngZone 解决了问题。
猜你喜欢
  • 2021-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-30
相关资源
最近更新 更多