如何修复 Angular Google 地图中的类型错误?

How to fix type error in Angular Google Maps?

我在我的应用程序中使用 Angular Google 地图,但我不能在我的代码中使用 google.maps.places.PlaceResult 作为重要变量的类型。


我正在实施此代码:(向下滚动以添加 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/

我正在地图上进行地点搜索,但出现此错误:

在此代码中:

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

      let autocomplete = new google.maps.places.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;
        });
      });
    });
  }

我只是照着例子做的,好像不认识google。你如何解决这个问题?

我希望按原样使用 link 中的示例,但我不能。

提前致谢!

要解决此问题,您需要在名为 types.

的文件夹内的根文件夹中添加一个名为 google-maps.d.ts 的文件

然后在该文件中添加以下代码:

google-maps.d.ts

import '@types/googlemaps';

declare global {
    interface Window {
        google: typeof google;
    }
}

这将允许您在打字稿中为变量指定类型,类型为 google.X.X。确保您已将类型安装到您的项目中,npm install --save @types/googlemaps

此外,请确保在 tsconfig.json 文件中添加 types 以将其指向包含以下代码的文件夹:

tsconfig.json

// tsconfig.json
compilerOptions: {
   ...
   "typeRoots": [
     "node_modules/@types",
     "types"
   ],
   ...
}

我从哪里得到答案,(通过 feilxmosh 向下滚动到第二个答案):

感谢@JensHabegger 向我发送了这个link。我回答了我自己的问题,因为 JensHabegger 没有。