首页 > 解决方案 > 无法在地理编码函数内分配组件变量值

问题描述

GetLocation(address: string) {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({ 'address': address }, (results, status) => {
    if (status == google.maps.GeocoderStatus.OK) {
      this.lat = results[0].geometry.location.lat(); 
      this.lng = results[0].geometry.location.lng();   <== this.lat value is undefined
    }
    else {
      alert("Something went wrong : " + status);
    }
  });
}

在这里,我无法在地理编码函数中分配组件级变量“lat”和“lng”的值。仅供参考:它里面的结果的位置对象中有值,但是在分配值之后它仍然是未定义的我不知道为什么?

标签: google-mapsangular6google-geocoder

解决方案


import { Component, OnInit, NgZone } from '@angular/core';  <= 1. I have to import NgZone

constructor(private ngZone: NgZone) { }  <= 2. declared it here

ngOnInit() { }

GetLocation(address: string) {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({ 'address': address }, (results, status) => this.ngZone.run(() => { <= 3. and used it here
    if (status == google.maps.GeocoderStatus.OK) {
      this.lat = results[0].geometry.location.lat();
      this.lng = results[0].geometry.location.lng();
    }
    else {
      alert("Something went wrong : " + status);
    }
  }));
}

我找到了解决方案。我必须从 '@angular/core' 导入 NgZone 并在回调函数中使用 this.ngZone.run() 函数,如 3. 提示。


推荐阅读