adding googlemaps to angular-cli

2019-05-07 10:13发布

问题:

I am trying to implement googlemaps to my angular-cli project. I know that there is a 'angular2-google-maps' component (github), but I need routes and more custom features.

I found two ways on implementing the map into an project:

1: stackoverflow: with a google api loader - but I couldn't figure out how to initialise google-maps...

2: with an DefinitelyTyped google.maps.d.ts. I installed it with --global (since ambient ist deprecated..) into my project and added the index.d.ts (for global) to the src/typings.d.ts and can use "google.map.." in an .ts file:

  myLatLng = {lat: -25.363, lng: 131.044};
  map:any;

  constructor() {
    this.map = new google.maps.Map(document.getElementById('map'), {
      center: this.myLatLng,
      zoom: 4
    });
  }

but if I build it with angular-cli it errors: "ReferenceError: google is not defined"

any ideas?

回答1:

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..