Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to load the google maps api into angular2?

I have played around with angular2 maps, but in the end I think I want to use the google maps api directly.

What's the best/right way to load this into angular 2? Currently I am loading it via a script tag, inserted into the index.html file, like so.

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

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">
</head>
<body>
    <script 
    src="https://maps.googleapis.com/maps/api/js?key=my_api_key">
    </script>
  <app-root>Loading...</app-root>
</body>
</html>

Then I create a map in a component inside the ngAfterViewInit() hook of the component that will hold the map.

ngAfterViewInit() {
    this.map = new google.maps.Map(this.mymap.nativeElement, {zoom: 4, center: {lat: -25.363, lng: 131.044} });
}

This seems to work, but adding the script tag does not seem like the right thing to do. I tried adding the script to the angular-cli.json scripts: [] array, but that does not seem to work (the call to new google.maps.Map() fails with google being undefined).

BTW, I installed the types via npm install --save @types/google-maps and they seem to be recognized.

like image 909
nPn Avatar asked Sep 19 '25 17:09

nPn


1 Answers

This is how I integrated google-maps:

  1. I created script load service, which loads scripts only when required -

    import { Injectable } from '@angular/core';

    @Injectable()
    export class ScriptLoadService {
    
      constructor() { }
    
      public loadScript(url, id, c): void {
        if (!document.getElementById(id)) {
          const script = document.createElement('script');
          script.type = 'text/javascript';
          script.src = url;
          script.id = id;
          if (c) {
            script.addEventListener('load', function (e) {
              c(null, e);
            }, false);
          }
          document.head.appendChild(script);
        }
      }
    
    }
    
  2. Add your googleMapURL in your environment file

googleMapURL: 'https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX&libraries=places'

  1. Now you can use use google maps api in any component by injecting ScriptLoadService and in ngOnInit or ngAfterViewInit call loadScript funcion:

    @ViewChild('mapElement') mapElm: ElementRef; // to display map

    constructor( private scriptLoadService: ScriptLoadService ) {} // inject the service
    
      ngAfterViewInit() {
        this.scriptLoadService.loadScript(environment.googleMapURL, 'google-map', () => {
          this.center = new google.maps.LatLng(
            this.lat,
            this.lng);
    
          // Create map
          this.map = new google.maps.Map(this.mapElm.nativeElement, {
            zoom: 18,
            center: this.center,
            disableDefaultUI: true,
            scrollwheel: false,
          });
    
          // Add Marker to current location detected by browser
          this.marker = new google.maps.Marker({
            position: this.center,
            map: this.map
          });
    });
    }
    

Hope this helps :)

like image 184
Ambikesh Singh Tomar Avatar answered Sep 22 '25 08:09

Ambikesh Singh Tomar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!