Using Google Maps Location In Angular

Introduction

In this blog, we will learn how to use Angular Google Maps Location in Angular code.

Step 1

First, we have to install npm commands in our project.

npm install @agm/core –save
 
This commands adds external dependency.
 

Step 2

Add app.module.ts page with the below code for importing the reference for Google Maps.

  1. import {  
  2.     AgmCoreModule  
  3. } from '@agm/core ';  
  4. @NgModule({  
  5.     imports: [  
  6.         AgmCoreModule.forRoot({  
  7.             apiKey: 'Your Google Api Key'  
  8.         })  
  9.     ],  
  10. })  

Step 3

Add your source component.ts page inside call AgmCoreModule,AgmMap,ViewChild, NgOnDestroy, triggerResize.

ViewChild returns the first element that matches a given component, directive, or template reference selector.

NgOnDestroy is called for cleaning up the logic when a component, directive, pipe or service is destroyed.

ngOnDestroy() is called just before component/directive is about to be destroyed by Angular. It can be used for the following purposes.

  1. import {  
  2.     Component,  
  3.     ViewChild,  
  4.     ElementRef,  
  5.     OnInit,  
  6.     Pipe,  
  7.     PipeTransform,  
  8.     ChangeDetectorRef  
  9. } from '@angular/core';  
  10. import {  
  11.     AgmCoreModule,  
  12.     AgmMap  
  13. } from '@agm/core';  
  14. @ViewChild(AgmMap) public agmMap: AgmMap;  
  15. public lat: number;  
  16. public lng: number;  
  17. zoom: number;  
  18. ngOnInit() {  
  19.     this.lat = 51.673858;  
  20.     this.lng = 7.815982;  
  21.     this.zoom = 16;  
  22.     this.agmMap.ngOnDestroy();  
  23.     this.agmMap.triggerResize(true);  
  24. }  

Step 4

Add the sourcecomponent.html page to the Google Maps HTML code.

Here, I have assigned latitude, longitude, and zoom level of Google Maps. The values have been mentioned.

  1. <agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom" [streetView]="true" [scrollwheel]="true" [zoomControl]="true">  
  2.     <agm-marker [latitude]="lat" [longitude]="lng"> </agm-marker>  
  3. </agm-map> 

 

Finally, I got the exact position from Google Maps. I hope this blog is helpful for you.
Next Recommended Reading How To Use .map() In Angular