问题
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