使用Angular进行反向地理编码

问题描述 投票:3回答:2

我在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 google-maps-api-3 geocoding reverse-geocoding
2个回答
3
投票

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

1) You're not in Angular's zone

更改变量以进行显示的代码未在Angular的区域内执行。当你在这里使用来自第三方库的回调时,往往会发生这种情况。

要修复,请注入NgZone并使用this.ngZone.run包装您想要在UI中反映的任何更改,如下面的代码段所示。

constructor(private ngZone: NgZone) {}

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

2) Wrong this

在某个地方,你已经失去了指向类实例的this,而你却将结果写入其他东西。你console.log工作,因为它也记录错误的this,而Angular没有显示任何东西,因为实际属性没有改变。


0
投票

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

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

ngOnInit() {
  this.locate();
}
© www.soinside.com 2019 - 2024. All rights reserved.