Typescript Error Cannot find name 'google' in ionic2 when using googlemaps javascript API

耗尽温柔 提交于 2020-02-23 08:59:49

问题


I am following Joshua Morony's Getting Started with Google Maps in Ionic 2 video tutorial. I want to use google maps in my application and i end up with a typescript error. this is a part of the pages/home/home.ts file

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);}

I tried npm install --save @types/googlemaps,

but it still gives me the same typescript error Typescript Error Cannot find name 'google'


回答1:


I solved it by installing:

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



回答2:


To expand on the answer from @suraj, you should have:

declare var google; 

outside of the class you are trying to use it in.

Just like in the Josh Morony video, I put it beneath the imports but before the class declaration and annotations (@Injectable() and so forth). I suppose it would still work if you put it above the imports or beneath the end of the class (and still outside of the class), if you were so inclined for whatever reason.




回答3:


npm install --save-dev @types/googlemaps

import {} from '@types/googlemaps';

from this answer

Or

in your component.ts file of your page declare it like this

declare var google; before export class component {}

An easy way Angular 6+ available in typescript is:

You only have to add this line at the beginning (meaning line 1, with nothing before) of your Typescript file :

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

And than

import {RemainingItems} from 'whicheverfolderyouwant';

Updated from




回答4:


You have to install types:

npm install --save-dev @types/googlemaps

And in your Typescript file where you use the namespace 'google':

[Angular 6+] Add this line at the beginning:

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

[Angular 5-] Add this line:

import {} from '@types/googlemaps';

from this answer




回答5:


No need to do some thing extra Just go into index.d.ts and paste this before declare namespace google.maps

declare module 'googlemaps';


来源:https://stackoverflow.com/questions/42173662/typescript-error-cannot-find-name-google-in-ionic2-when-using-googlemaps-javas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!