angular - 如何修复 Angular Google map 中的类型错误?

标签 angular google-maps google-places angular-google-maps

我在应用中使用 Angular Google map ,但无法使用 google.maps.places.PlaceResult 作为代码中重要变量的类型。


我正在实现此代码:(向下滚动到添加位置/地点搜索栏)

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

我正在 map 上进行地点搜索,但收到此错误:

enter image description here

在此代码中:

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。你如何解决这个问题?

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

提前致谢!

最佳答案

要解决此问题,您需要在名为 types 的文件夹内的根文件夹中添加一个名为 google-maps.d.ts 的文件。

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

google-maps.d.ts

import '@types/googlemaps';

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

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

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

tsconfig.json

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

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

How to install Typescript typings for google maps

感谢 @JensHabegger 向我发送此链接。我回答了我自己的问题,因为 JensHabegger 没有回答。

关于angular - 如何修复 Angular Google map 中的类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56653284/

相关文章:

angular - 如何在所有组件中重用公共(public)变量名和函数

android - 如何在 Autocomplete Places _ Places API 中获取城市和州名称

javascript - Google 自动完成 API 首先返回我所在州的地点,而不是最多 "expected"地点

google-places-api - google-places-API 中已弃用的杂货店或超市类型的新类型

angular - 无法读取 null TypeError : Cannot read property 的属性 'config'

angular - 在同级组件 Angular 2 之间进行通信

angular - Chrome 开发工具可以帮助找出 Angular 组件名称吗?

javascript - 拖动后的谷歌地图标记位置

javascript - vue导入失败 'marker-animate-unobtrusive'

java - Google map Activity 显示空白屏幕