Angular 8 Google Maps Tutorial with Example

Angular 8 Google Maps Tutorial with Example

In this article, you'll learn how to integrate Google Maps in Your Angular 8 Application using this example. In this Angular Google Maps integration tutorial, we would love to share each things step by step with example.

In this article, you'll learn how to integrate Google Maps in Your Angular 8 Application using this example. In this Angular Google Maps integration tutorial, we would love to share each things step by step with example.

Before start integrating of Google maps in your Angular 8 Application example, We need a Angular 8 Project.

So, Let’s get started Angular 8 Google Maps

First, let’s add a placeholder for Google Map in this Angular 8 application example.

Open app.component.html file and put the below html markup

<div class="row mt-5">
    <div class="col-md-9 mx-auto">
        <h2 class="text-left">Google Map</h2>
        <div class="card mt-3">
            <div class="card-body">
                <div #mapRef style="width:100%;height:400px"></div>
            </div>
        </div>
    </div>
</div>

Next, Open the app.component.ts file and add the below code

@ViewChild('mapRef', {static: true }) mapElement: ElementRef;

Access <div #mapRef>: mapElement is a reference to <div #mapRef> inside app.component.html file. ViewChild directive creates a direct link between

element and a mapElement member variable.

Loading the Maps JavaScript API

We are going to load the Maps JavaScript** [API](https://morioh.com/topic/api "API**") in the app.module.tsfile. If you don’t want to load it globally. You can create a new component and load it.

So, open the app.component.ts file and put the below two methods on this

renderMap() {

  window['initMap'] = () => {
    this.loadMap();     
  }
  if(!window.document.getElementById('google-map-script')) {
    var s = window.document.createElement("script");
    s.id = "google-map-script";
    s.type = "text/javascript";
    s.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyDRmqZ-1VD-DbsccElMGtMtlRz9FndbPB4&amp;callback=initMap";

    window.document.body.appendChild(s);
  } else {
    this.loadMap();
  }
}
loadMap = () => {
  var map = new window['google'].maps.Map(this.mapElement.nativeElement, {
    center: {lat: 24.5373, lng: 81.3042},
    zoom: 8
  });

  var marker = new window['google'].maps.Marker({
    position: {lat: 24.5373, lng: 81.3042},
    map: map,
    title: 'Hello World!',
    draggable: true,
    animation: window['google'].maps.Animation.DROP,
  });

  var contentString = '<div id="content">'+
  '<div id="siteNotice">'+
  '</div>'+
  '<h3 id="thirdHeading" class="thirdHeading">W3path.com</h3>'+
  '<div id="bodyContent">'+
  '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>'+
  '</div>'+
  '</div>';

  var infowindow = new window['google'].maps.InfoWindow({
    content: contentString
  });

    marker.addListener('click', function() {
      infowindow.open(map, marker);
    });

}

In order to do any kind of interaction with the Maps API, you need an API *key from *Google. Follow the instructions here to get that set up. After the setup complete, You need to replace YOUR_API_KEYwith google map key.

You may noticed that, we have load the Google Maps JavaScript CDN under the renderMap method.

The renderMap method will check that the Google Maps JavaScript CDN is already loaded or not. If not then it will load the Google Maps JavaScript CDN. If already loaded then will call the loadMapmethod.

The loadMap will draw the map.

Next, We will call the renderMap method under ngOnInit method. like this

ngOnInit() {
    this.renderMap();
}

Angular 8 will invoked the ngOnInit only once when the directive is instantiated.

After above changes our app.component.ts file will looks like this

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

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

  @ViewChild('mapRef', {static: true }) mapElement: ElementRef;

  constructor() {};

  ngOnInit() {   
    this.renderMap();
  }

  loadMap = () => {
    var map = new window['google'].maps.Map(this.mapElement.nativeElement, {
      center: {lat: 24.5373, lng: 81.3042},
      zoom: 8
    });

    var marker = new window['google'].maps.Marker({
      position: {lat: 24.5373, lng: 81.3042},
      map: map,
      title: 'Hello World!',
      draggable: true,
      animation: window['google'].maps.Animation.DROP,
    });

    var contentString = '<div id="content">'+
    '<div id="siteNotice">'+
    '</div>'+
    '<h3 id="thirdHeading" class="thirdHeading">W3path.com</h3>'+
    '<div id="bodyContent">'+
    '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>'+
    '</div>'+
    '</div>';

    var infowindow = new window['google'].maps.InfoWindow({
      content: contentString
    });

      marker.addListener('click', function() {
        infowindow.open(map, marker);
      });

  }
  renderMap() {

    window['initMap'] = () => {
      this.loadMap();     
    }
    if(!window.document.getElementById('google-map-script')) {
      var s = window.document.createElement("script");
      s.id = "google-map-script";
      s.type = "text/javascript";
      s.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyDRmqZ-1VD-DbsccElMGtMtlRz9FndbPB4&amp;callback=initMap";

      window.document.body.appendChild(s);
    } else {
      this.loadMap();
    }
  }

}

Running application

Run application using ng serve –o and you should see Google Maps inside browser. Congrats!! See, it was easy.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Getting started with Angular Google Maps component

The new Angular Component release introduces the second official @angular/component component, a Google Maps component. In this post, we take a look at getting started with the Angular Google Maps component.