I'm using the @typings/googlemaps typing for an Angular application, which when serving runs and returns no warnings or errors.
However, I'd like to create some unit tests for my components, and Karma cant launch, producing errors like:
ERROR in: ... Cannot find namespace 'google'.
I followed this post and others like it to install the typing and continue my work.
Adding declare var google:any
to the typings.d.ts won't work since it is already declared in the typing file, and the 'Duplicate identifier' compile error is given.
Any suggestions?
EDIT 1:
An excerpt of code on my google-maps.service.ts, one of the files giving an error. I don't import googlemaps, as it's not necessary since it's a typing by my understanding.
import {Injectable} from "@angular/core";
import {environment} from "../../../environments/environment";
import {Http} from "@angular/http";
import {forEach} from "@angular/router/src/utils/collection";
@Injectable()
export class GoogleMapsService {
scriptLoadingPromise: Promise<void>;
api_key = '';
url = '';
map: google.maps.Map;
markers: Array<google.maps.Marker>;
bounds: google.maps.LatLngBounds;
geocoder: google.maps.Geocoder;
constructor(private http: Http) {
this.api_key = '1234';
this.url = 'https://maps.googleapis.com/maps/api/js';
this.markers = new Array();
// Loading script
this.load().then(() => {
this.geocoder = new google.maps.Geocoder();
});
}
}
getScriptSrc(callbackName: string): string {
return `https://maps.googleapis.com/maps/api/js?key=${this.api_key}&callback=${callbackName}`;
};
onReady(): Promise<void> {
return this.scriptLoadingPromise;
};
load(): Promise<void> {
if (this.scriptLoadingPromise) {
return this.scriptLoadingPromise;
}
const script = window.document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.defer = true;
const callbackName = 'googleMapsServiceCallback';
script.src = this.getScriptSrc(callbackName);
this.scriptLoadingPromise = new Promise<void>((resolve: Function, reject: Function) => {
(<any>window)[callbackName] = () => {
resolve();
};
script.onerror = (error: Event) => {
reject(error);
};
});
window.document.body.appendChild(script);
return this.scriptLoadingPromise;
}
EDIT 2: I updated the code above. It uses the same structure as the Angular 2+ Maps project, with reference to the code here. There aren't any pre-compilation errors thrown because the 'google' keyword is accounted for in the typing.