Angular2 找不到命名空间 'google'

Angular2 Cannot find namespace 'google'

我正在使用 angular2-google-maps 和最新版本的 Angular2。我正在尝试将一些本地地图组件功能转换为它们自己文件中的服务 maps.service.ts。例如:

map.component.ts

getGeoLocation(lat: number, lng: number) {
if (navigator.geolocation) {
    let geocoder = new google.maps.Geocoder();
    let latlng = new google.maps.LatLng(lat, lng);
    let request = { latLng: latlng };
    geocoder.geocode(request, (results, status) => {
      if (status == google.maps.GeocoderStatus.OK) {
        let result = results[0];
        if (result != null) {
          this.fillInputs(result.formatted_address);
        } else {
          alert("No address available!");
        }
      }
    });
}
}

变成这样的东西:maps.service.ts

getGeoLocation(lat: number, lng: number): Observable<google.maps.GeocoderResult[]> {
    let geocoder = new google.maps.Geocoder();
    let latlng = new google.maps.LatLng(lat, lng);
    let request = { latLng: latlng };
    return new Observable((observer: Observer<google.maps.GeocoderResult[]>) => {
        geocoder.geocode({ request }, (
            (results: google.maps.GeocoderResult[], status: google.maps.GeocoderStatus) => {
                if (status == google.maps.GeocoderStatus.OK) {
                    observer.next(results);
                    observer.complete();
                } else {
                    console.log('Geocoding service failed due to: ' +status);
                    observer.error(status);
                }
            }
        ));
    });
}

我遇到的问题是当我尝试使用 Observer<google.maps.GeocoderResult[]> 时无法识别 google 变量。我在服务 class 之外也有 declare var google: any;

google 变量在我的 map.componenet.ts 中有效,但在 maps.service.ts 中无法识别。

添加

declare var google: any;

TypeScript 导入后

另见 https://github.com/SebastianM/angular2-google-maps/issues/689

我遇到了同样的问题 我试过了:

declare var google: any;

但它对我不起作用。
我找到了这个 并且对我有用。
首先确保你安装了 google maps
npm install @types/googlemaps --save --dev

的类型

--dev flag is deprecated. Use npm install @types/googlemaps --save-dev

然后在你的控制器中

import {} from '@types/googlemaps';

它也适用于我:

首先在项目根目录下的 cmd 中为 google 地图安装 typings

npm install @types/googlemaps --save --dev

然后在下面添加您的 .ts 组件文件:

import {} from '@types/googlemaps';

为了防止其他人因这个问题遭受更多痛苦。

npm install @google/maps

https://www.npmjs.com/package/@google/maps

然后:

import { google } from '@google/maps';

基本上我们从包 @google/maps.

导入 google 对象

2018 年 @types/googlemaps 停止工作后进行测试。

我和 Angular 6 有类似的问题,我做了上面提到的所有可能的解决方案,但没有成功。 最后,我设法通过将 googlemaps 添加到 tsconfig.apptsconfig.spec 文件中的 types 来解决这个问题。 希望对其他人有帮助。

Angular 6 和 7 个步骤(也应该适用于所有其他 Angular 版本):

  1. npm install @types/googlemaps --save-dev
  2. 分别在tsconfig.app.jsontsconfig.spec.json
  3. 中的types数组中添加googlemaps
  4. 重新启动 npm 服务器

最后应该是这样的:

You can delete both declaration types from the components: import {} from '@types/googlemaps'; declare var google: any; You don't have to include any of them.

PS:如果您正在使用 agm-s GoogleMapsAPIWrapper.getNativeMap(),您必须在使用之前转换地图对象。例如打开交通层:

this.apiWrapper.getNativeMap().then(map => {
    this.trafficLayer = new google.maps.TrafficLayer();
    const gMap: any = map;
    this.trafficLayer.setMap(gMap as google.maps.Map);
});

在我的例子中,我遇到了两种类型的错误:

  • 找不到命名空间google
  • 找不到名字google

因为在我的代码中我使用:

let autocomplete = new google.maps.places.Autocomplete(...)

let place: google.maps.places.PlaceResult = autocomplete.getPlace();

所以通过添加这个修复它:

declare var google: any;

declare namespace google.maps.places {
    export interface PlaceResult { geometry }
}
`
import { Observable } from 'rxjs';
import { GoogleMapsAPIWrapper, MapsAPILoader } from '@agm/core';
import { Injectable, NgZone } from '@angular/core';
declare var google: any;

@Injectable({
  providedIn: 'root'
})
export class MapService extends GoogleMapsAPIWrapper {
  geocoder: Promise<any>;
  constructor(private __loader: MapsAPILoader, private __zone: NgZone) {
    super(__loader, __zone);
    this.geocoder = this.__loader.load().then(() => new google.maps.Geocoder());
  }

  getLatLan(address: string): Observable<any> {
    return Observable.create(observer => {
      this.geocoder.then((geocoder) => {
        geocoder.geocode({ 'address': address }, (results, status) => {
          if (status === google.maps.GeocoderStatus.OK) {
            observer.next(results[0].geometry.location);
            observer.complete();
          } else {
            console.error('Error - ', results, ' & Status - ', status);
            observer.next({});
            observer.complete();
          }
        });
      });
    });
  }
}`

这是一项具有获取地址和return lan 和lat 的方法的服务。

ERROR: [ts] Cannot import type declaration files. Consider importing ‘googlemaps’ instead of ‘@types/googlemaps’

解决方案:将import {} from ‘@types/googlemaps’;改为

/// <reference types=”@types/googlemaps” />

ERROR: while compiling, error TS2304: Cannot find name ‘google’.

解决方案:在@types/googlemaps参考

下方添加declare var google: any;
ERROR: while compiling error TS2503: Cannot find namespace ‘google’.

解决方案:添加到tsconfig.app.json:"types": ["googlemaps"] 并重新启动


ERROR: map doesn’t load correctly and in the web browser console you read “Google Maps Javascript API Warning: NoApiKeys”

解决方案:在index.html中的javascript文件中添加一个有效的api键,应该 看起来像这样 <script type=”text/javascript” src=”http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE"></script> 你可以从这里 https://developers.google.com/maps/documentation/javascript/get-api-key

得到一个 API 密钥
ERROR:Cannot find name 'google'

好吧,这是为了防止你刚刚安装了以下类型:

npm i -D @types/google.maps

并且您尝试使用它们。有时 tsconfig.app.json 中有空类型数组,这会阻止自动导入。删除 "types": [] 并且可以工作。它对我有用过一次。

直接解决,在tsconfig.app.json中的类型数组中添加"googlemaps"。而且我不需要声明任何东西,比如 declare var google: any;。只需在 tsconfig 中添加 googlemaps 即可。

"types": ["googlemaps"]

如果有人为此苦苦挣扎,因为即使在安装类型并将它们添加到 tsconfig 之后,Webstorm 也会取消对代码的标记...重新启动 Webstorm。我花了一个小时。

注意解决了我的问题。 在遵循最高评价的答案后仍然没有工作只有在添加这个

之后才有效

npm i @types/googlemaps@3.39.13 --save-dev

确保在 ng serve 之前 运行 并确保在 运行ning 时重新启动服务器。

安装reference

npm i -D @types/google.maps

在您的 Typescript 文件的开头(即第 1 行,之前没有任何内容)添加此行:

/// <reference types="@types/google.maps" />

Triple Slash Documentation

Source