Angular 中未定义的地理编码器类型错误

Type Error of Geocoder undefined in Angular

我的 Angular 项目中的 Geocoder 正在崩溃,因为它未定义。我试过这个:

但是我先初始化或者赋值都不行。两者都不行。

我的代码,第一行错误:

private geoCoder = new google.maps.Geocoder();

  @ViewChild('search', { static: false })
  public searchElementRef: ElementRef;

  constructor(private maps: MapsAPILoader, private ngZone: NgZone){ }

  ngOnInit() {
    // Load places autocomplete
    this.maps.load().then(() => {
      this.setCurrentLocation();

      let autocomplete = new google.place.Autocomplete(this.searchElementRef.nativeElement, {
        types: ["address"]
      });

      autocomplete.addListener("place_changed", () => {
        this.ngZone.run(() => {
          // Get the place result
          let place: google.maps.places.PlaceResult = autocomplete.getPlace();

          // Verify result
          if (place.geometry === undefined || place.geometry === null) {
            return;
          }

          // Set latitude, longitude & zoom
          this.userLat = place.geometry.location.lat();
          this.userLng = place.geometry.location.lng();
          this.zoom = 12;
        });
      });
    });
  }

  // Get Current Location Coordinates
  private setCurrentLocation() {
    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition((position) => {
        this.userLat = position.coords.latitude;
        this.userLng = position.coords.longitude;
        this.zoom = 15;
      });
    }
  }

getaddress(latitude, longitude) {
    this.geoCoder.geocode({ "location": { lat: latitude, lng: longitude } }, (results, status) => {
      console.log(results);
      console.log(status);

      if (status === "Ok") {
        if (results[0]) {
          this.zoom = 12;
          this.address = results[0].formatted_address;
        } else {
          window.alert("No results found.");
        }
      } else {
        window.alert("Something went wrong, please try again.");
      }
    });
  }

发件人(向下滚动到添加 Location/Places 搜索栏):

https://www.freakyjolly.com/angular-7-6-add-google-maps-in-angular-2-plus-applications-using-angular-google-maps-module-agm-core-easily/

如何防止崩溃?谢谢!

编辑:固定: https://stackblitz.com/edit/angular-rhbjrx

等待地图加载器,然后在ngOnInit():

中分配Geocoder()
this.mapsAPILoader.load().then(() => {
      this.setCurrentLocation();
      this.geoCoder = new google.maps.Geocoder;
  .....
}

确保安装:

npm install @types/googlemaps --save-dev

编辑:

在 module.ts 中正确导入:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AgmCoreModule } from '@agm/core';

import { AppComponent } from './app.component';

@NgModule({
  imports:      [ 
    AgmCoreModule.forRoot({
      apiKey: 'AIzaSyCnn-_D68N95BaSpYRYn1E3N_DHGs1vz0Y',
      libraries: ["places"]
    }),
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
   ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

错误发生在 Geocoder 初始化时,Google 地图 API 尚未加载。在 Angular Google Maps 库中,可以利用 MapsAPILoader 服务来确保 Google 加载地图 API,然后初始化 Geocoder

this.mapsAPILoader.load().then(() => {
   this.geoCoder = new google.maps.Geocoder;  
});

这是一个示例(改编自 official Geocoding Service example),它演示了如何将 Goolge 地图地理编码服务与 Angular Google 地图

一起使用
export class AppComponent implements OnInit {
  center = {lat: -34.397, lng: 150.644};
  position= {lat: null, lng: null};
  zoom: number = 8;
  address: string;
  private geoCoder;


  constructor(
    private mapsAPILoader: MapsAPILoader,
    private ngZone: NgZone
  ) { }


  ngOnInit() {
    this.mapsAPILoader.load().then(() => {
       this.geoCoder = new google.maps.Geocoder;  
    });
  }


  geocodeAddress(addressInput) {
    const address = addressInput.value;
    this.geoCoder.geocode({'address': address}, (results, status) => {
          if (status === 'OK') {
            this.position = {
              "lat": results[0].geometry.location.lat(),
              "lng": results[0].geometry.location.lng()
            }
          } else {
            alert('Geocode was not successful for the following reason: ' + status);
          }
    });
  }

}

这里是 demo

您需要确保您有正确的导入语句并使用正确的库。

由于@agm中没有定义Geocoder,@types/googlemaps中有定义,没有的话需要下载:npm install --save @types/googlemaps.

使用此导入语句:import { } from 'googlemaps'; 创建此文件后,index.d.ts 在您的 src 文件夹或根文件夹中,并在其中声明:

index.d.ts

declare module "googlemaps";

并确保将地理编码器放在方括号中:Geocoder()

这应该可以解决问题,就像我一样。

https://stackblitz.com/edit/angular-rhbjrx