【问题标题】:Typescript Error Cannot find name 'google' in ionic2 when using googlemaps javascript API打字稿错误使用googlemaps javascript API时在ionic2中找不到名称'google'
【发布时间】:2017-06-29 15:28:04
【问题描述】:

我正在关注 Joshua Morony 在 Ionic 2 视频教程中的 Google 地图入门。 我想在我的应用程序中使用谷歌地图,但最终出现打字错误。这是一部分 pages/home/home.ts 文件

initMap(){
let latLng= new google.maps.LatLng(6.929848, 79.857407);

let mapOpt={
  center : latLng,
  zoom : 15,
  mapTypeId :google.maps.MapTypeId.ROADMAP
};

this.map= new google.maps.Map(this.mapElement.nativeElement,mapOpt);}

我试过npm install --save @types/googlemaps

但它仍然给我同样的打字稿错误 打字稿错误 找不到名称“google”

【问题讨论】:

  • 现有 2 个答案的问题在于,它们破坏了拥有 npm install --save @types/googlemaps 的意义。你说你有这个,他们说使用any。它不能解决问题。您甚至可以在 IDE 中右键单击并查看 google 声明,但 Ionic2 看不到它。
  • 它在 Ionic 3 中对我有用,请参考这个答案stackoverflow.com/questions/51084724/…

标签: google-maps angular typescript ionic2 typescript-typings


【解决方案1】:

要扩展@suraj 的答案,您应该:

declare var google; 

在你尝试使用它的类之外。

就像在 Josh Morony 视频中一样,我将它放在导入的下方,但在类声明和注释之前(@Injectable() 等等)。我想如果你把它放在 import 之上或类的末尾(并且仍然在类之外),它仍然可以工作,如果你出于某种原因如此倾向于。

【讨论】:

    【解决方案2】:

    我通过安装解决了:

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

    【讨论】:

    • 为我工作 2 :)
    • @Eli 我遇到了同样的问题,你能帮帮我吗?
    【解决方案3】:
    npm install --save-dev @types/googlemaps
    
    import {} from '@types/googlemaps';
    

    来自this answer

    或者

    在您页面的component.ts 文件中这样声明

    declare var google;export class component {} 之前

    在 typescript 中使用 Angular 6+ 的简单方法是:

    您只需在开头添加这一行(意思是 您的 Typescript 文件的第 1 行,之前没有任何内容:

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

    然后

    import {RemainingItems} from 'whicheverfolderyouwant';

    Updated from

    【讨论】:

      【解决方案4】:

      无需做额外的事情只需进入 index.d.ts 并粘贴此在声明命名空间 google.maps

      declare module 'googlemaps';
      

      【讨论】:

        【解决方案5】:

        你必须安装类型:

        npm install --save-dev @types/googlemaps
        

        在您使用命名空间“google”的 Typescript 文件中:

        [Angular 6+] 在开头添加这一行:

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

        [Angular 5-] 添加这一行:

        import {} from '@types/googlemaps';
        

        from this answer

        【讨论】:

          【解决方案6】:

          新版本!

          @types/googlemaps 已被弃用,您需要安装不同的库:

          npm install @types/google.maps

          在文件的第一行,您需要添加一个三斜杠指令:

          /// &lt;reference types="@types/google.maps" /&gt;

          【讨论】:

            猜你喜欢
            • 2017-06-18
            • 1970-01-01
            • 2020-01-29
            • 2023-03-17
            • 2017-12-01
            • 1970-01-01
            • 2017-04-08
            • 2017-08-27
            • 2018-03-01
            相关资源
            最近更新 更多