Embedding Google Map sometimes give error in Angular 4

时间:2017-06-09 12:49:01

标签: angular google-maps

I am trying to embed Google Map into my angular 4 project. Most of the time it works but sometimes it gives following error:

ERROR Error: Uncaught (in promise): ReferenceError: google is not defined .......

Code snippet from my angular project:

index.html:

 <!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>My Angular Project</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

<script src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_MAP_KEY"
  async defer></script>
</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>

(I have removed my Google map access key from above pasted code)

map.component.ts:

import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

declare var google;

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit, AfterViewInit {

  @ViewChild('map') mapElement: ElementRef;
  map: any;

  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit(){
    this.initMap();
  }

  initMap() {
    this.map = new google.maps.Map(this.mapElement.nativeElement, {
      center: { lat: -34.397, lng: 150.644 },
      zoom: 8
    });

  }
}

map.component.html:

<div #map id="map"></div>

Most of the time above code works but sometimes it doesn't. I think this might be because sometimes this.initMap() execute before <script src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_MAP_KEY" async defer></script> is fully loaded. To avoid this I have used ngAfterViewInit() but then also it is not working.

Please suggest right method to do this.

Error screenshot: Error screenshot

1 个答案:

答案 0 :(得分:2)

I've never personally enjoyed implementing Google Maps into Angular projects, so I've been primarily using this package. And totally recommend you trying it. It should simplify your map initialization with it's custom map components. So all you'd need to do is...

<sebm-google-map [latitude]="-34.397" [longitude]="150.644"></sebm-google-map>