Here a step by step guide to add a google maps component to angular-cli project.
Step1 : install google.maps from DefinitelyTyped:
typings i dt~google.maps --global --save
Step2 : if you have an older typings installed add
/// <reference path="../typings/index.d.ts" />
to your src/typings.d.ts
Step3 : generate new component
ng g component google-maps
Add the following code to:
.ts :
height = '100px';
myLatLng = {lat: -25.363, lng: 131.044};
map:any;
constructor(private googleApi:GoogleApiService) {}
ngOnInit() {
this.googleApi.initMap().then(() => {
let latlng = new google.maps.LatLng(this.myLatLng.lat, this.myLatLng.lng);
this.map = new google.maps.Map(document.getElementById('map'), {
center: latlng,
zoom: 4
});
new google.maps.Marker({
position: latlng,
map: this.map,
title: 'Hello World!'
});
});
}
.html :
<div id="map" [style.height]="height"></div>
Step4 : generate new service
ng g service google-maps/shared/google-api
Add GoogleApiService + HTTP_PROVIDERS to src/main.ts
code :
const API_KEY = '[insert your code]';
const url = 'https://maps.googleapis.com/maps/api/js?key='+ API_KEY +'&callback=initMap';
@Injectable()
export class GoogleApiService {
private loadMap: Promise<any>;
constructor(private http:Http) {
this.loadMap = new Promise((resolve) => {
window['initMap'] = () => {
resolve();
};
this.loadScript()
});
}
public initMap():Promise<any> {
return this.loadMap;
}
private loadScript() {
let script = document.createElement('script');
script.src = url;
script.type = 'text/javascript';
if (document.body.contains(script)) {
return;
}
document.getElementsByTagName('head')[0].appendChild(script);
}
}
Maybe you need to delete some lines from the spec.ts files.
But then you can add the GoogleMapsComponent as a directive.
- it is super easy to expand with routes etc.
Maybe if I have time I upload a current version of my GoogleMapsComponent to github..