How to show Google map in Angular 14+
Tags: angular
Published: 2023-02-02 10:59:30

<p class="paragraph"> In this article, we will learn how to show Google Map using javascript API step by step. </p><h2>Show Google map in Angular 14+</h2><p class="paragraph"> Create a New map component </p><pre><code class="code-block">ng g c map</code></pre><p class="paragraph"> Update map.component.html </p><pre><code class="code-block">&lt;div class="map" #map&gt;&lt;/div&gt;</code></pre><p class="paragraph"> Generate Google Maps service </p><pre><code class="code-block">ng g service services/google-maps/google-maps</code></pre><p class="paragraph"> It will Create <b>google-maps</b> service inside the services folder. </p><p class="paragraph"> Now replace this code with<code class="inline-code">&nbsp;google-maps.service.ts</code>&nbsp; </p><pre><code class="code-block">import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root',
})
export class GoogleMapsService {
  constructor() {}

  loadGoogleMaps(): Promise&lt;any&gt; {
    const win = window as any;
    const gModule = win.google;
    if (gModule &amp;&amp; gModule.maps) {
      return Promise.resolve(gModule.maps);
    }

    return new Promise((resolve, reject) =&gt; {
      const script = document.createElement('script');
      script.src =
        'https://maps.googleapis.com/maps/api/js?key=' +
        environment.googleMapsApiKey +
        '&amp;libraries=places';
      script.async = true;
      script.defer = true;
      document.body.appendChild(script);

      script.onload = () =&gt; {
        const loadedGoogleModule = win.google;
        if (loadedGoogleModule &amp;&amp; loadedGoogleModule.maps) {
          resolve(loadedGoogleModule.maps);
        } else {
          reject('Google Map SDK is not Available');
        }
      };
    });
  }

}
</code></pre><p class="paragraph"> Then update&nbsp;<code class="inline-code">map.component.ts</code> </p><pre><code class="code-block">import {
  AfterViewInit,
  Component,
  ElementRef,
  EventEmitter,
  Input,
  OnInit,
  Output,
  Renderer2,
  ViewChild,
} from '@angular/core';
import { GoogleMapsService } from 'src/app/services/google-maps/google-maps.service';

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss'],
})
export class MapComponent implements OnInit, AfterViewInit {
  @ViewChild('map', { static: true }) mapElementRef: ElementRef;
  googleMaps: any;
  map: any;
  center = { lat: 23.01997577399075, lng: 73.07245691797758 };
  
  constructor(
    private maps: GoogleMapsService,
    private renderer: Renderer2
  ) {}

  ngOnInit(): void {}
  ngAfterViewInit() {
    this.loadMap();
  }

  async loadMap() {
    try {
      let googleMaps: any = await this.maps.loadGoogleMaps();
      this.googleMaps = googleMaps;
      const mapEl = this.mapElementRef.nativeElement;

      const location = new googleMaps.LatLng(this.center.lat, this.center.lng);
      this.map = new googleMaps.Map(mapEl, {
        center: location,
        zoom: 15,
        scaleControl: false,
        streetViewControl: false,
        zoomControl: false,
        overviewMapControl: false,
        mapTypeControl: false,
        mapTypeControlOptions: {
          mapTypeIds: [googleMaps.MapTypeId.ROADMAP, 'mapId'],
        },
      });
      const style = [
        {
          featureType: 'all',
          elementType: 'all',
          stylers: [{ saturation: -100 }],
        },
      ];

      var mapType = new googleMaps.StyledMapType(style, { name: 'Grayscale' });
      this.map.mapTypes.set('mapId', mapType);
      this.map.setMapTypeId('mapId');
      this.renderer.addClass(mapEl, 'visible');
    } catch (e) {
      console.log(e);
    }
  }

}
</code></pre><p class="paragraph"> Now update&nbsp;<code class="inline-code">map.component.scss</code> </p><pre><code class="code-block">.map {
    height: 30vh;
    width: 100%;
    background-color: transparent;
}
.map.visible {
  opacity: 1;
}
</code></pre><p class="paragraph"> Now your map will be visible on browser </p><h2>How to add a Marker in Google Maps?</h2><p class="paragraph"> Add the addMarker function as below in <code class="inline-code">map.componenets.ts</code> as below: </p><pre><code class="code-block">  addMarker(location) {
    let googleMaps: any = this.googleMaps;
    const icon = {
      url: 'assets/icons/location-pin.png',
      scaledSize: new googleMaps.Size(50, 50),
    };
    this.marker = new googleMaps.Marker({
      position: location,
      map: this.map,
      icon: icon,
      draggable: true,
      animation: googleMaps.Animation.DROP,
    });
  }</code></pre><p class="paragraph"> Then call this function at bottom of&nbsp;loadMap function </p><pre><code class="code-block">this.addMarker(location);</code></pre><p class="paragraph"> Now you can also see the marker on the map at the center position. </p>