javascriptangulargoogle-mapsgoogle-maps-api-3

Load Google Maps JS API in Angular component


How is it possible to load an external js file, from a url in an Angular component?

To be specific, I'm trying to load google-maps-api to my angular project. Currently, I'm doing it in my index.html like this:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
</script>

Note: I'm aware of angular-maps. That's not an option.


Solution

  • A solution is to create the script tag dynamically in ngAfterViewInit()

    import { DOCUMENT } from '@angular/common';
    ...
    
    constructor(private @Inject(DOCUMENT) document, 
                private elementRef:ElementRef) {};
    
    ngAfterViewInit() {
      var s = this.document.createElement("script");
      s.type = "text/javascript";
      s.src = "https://maps.googleapis.com/maps/api/js?key=API_KEY";
      this.elementRef.nativeElement.appendChild(s);
    }
    

    See also https://github.com/angular/angular/issues/4903

    Update

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

    export class GoogleComponent implements OnInit {
      @ViewChild("mapRef") mapRef: ElementRef;
      constructor() { }
    
      ngOnInit() {
        this.showMap();
      }
    
      showMap() {
        console.log(this.mapRef.nativeElement);
        const location = { lat: 28.5355, lng: 77.3910 };
        var options = {
          center: location,
          zoom: 8
        }
    
        const map = new google.maps.Map(this.mapRef.nativeElement, options);
        this.addMarket(map, location);
      }
      addMarket(pos, map) {
        return new google.maps.Marker({
          position: pos,
          map: map,
        });
      }
    }