Get Current Location In Angular

Introduction

 
In this article, we are going to learn how to add Google maps in an Angular project. The steps are as follows.
 

Implementation

 
Step 1
 
Using the below command, create the Angular App.
 
Get Current Location In Angular
 
Step 2
 
Open the project which you have created in Visual Studio code and install the agm library using the following command “npm i @agm/core”.
 
Get Current Location In Angular
 
Step 3
 
Install the Google map reference npm using the following command.

Get Current Location In Angular
 
Step 4
 
Open the tsconfig.app.json in your project and update the following reference code.
  1. {  
  2.   "extends""./tsconfig.json",  
  3.   "compilerOptions": {  
  4.     "outDir""./out-tsc/app",  
  5.     "types": ["googlemaps"]  
  6.   },   
What is tsconfig.app.json ?
 
It holds the root files and the compiler options.
 
Step 5
 
Like the above steps, open tsconfig.spec.json file in your project and update the following reference code.
  1. {  
  2.   "extends""./tsconfig.json",  
  3.   "compilerOptions": {  
  4.     "outDir""./out-tsc/spec",  
  5.     "types": [  
  6.       "jasmine",  
  7.       "node",  
  8.       "googlemaps"  
  9.     ]  
  10.   },  
What is tsconfig.spec.json ?
 
File has a setting to convert your typescript code into javascript code to make the browser understand our code.
 
Step 6
 
Now open your app.module.ts file & add the agm library file using the following line: 
  1. import {AgmMap, MouseEvent,MapsAPILoader  } from '@agm/core';  
How To Get Map Api Key
 
A) Visit Google developer console page or Click here
 
B) Open the menu & click the APIs & Services and select "Credentials"
 
Get Current Location In Angular
 
C) On the credentials page, open the "CREATE CREDENTIALS" and select the API key.
 
Get Current Location In Angular
 
D) Once the process is done, the API code will be generated and can be seen in the list of new APIs in the same credentials page.
 
Step 7
 
Once you get the Googlemap API key, paste the app.module.ts with the below code.
  1. imports: [  
  2.     AgmCoreModule.forRoot({  
  3.       apiKey: 'Paste Your Api Key'  
  4.     }),  
  5.   ],  
Get Current Location In Angular
 
Step 8
 
Open the app.component.ts file which you can add in the agmmap reference file.
  1. import {AgmMap, MouseEvent,MapsAPILoader  } from '@agm/core';  
Step 9
 
A) After then we can declare the agmmap for view child.
  1. @ViewChild(AgmMap,{statictrue}) public agmMap: AgmMap;  
B) And assgin the mapsAPIloader in constructor.
  1. constructor(private apiloader: MapsAPILoader) {}  
Step 10
 
Now, open app.component.html file & add the below code. Similarly, open the app.component.ts file.
  1. <form>  
  2.   <agm-map style="height: 300px;" [latitude]="lat" [longitude]="lng" [zoom]="zoom" (mapClick)="mapClicked($event)">  
  3.   <agm-marker  [latitude]="lat" [longitude]="lng"></agm-marker>  
  4.         </agm-map>  
  5. </form>  
Step 11
 
Let us open the app.component.ts file by adding the following code which is used to get the current latitude and longitude.
 
After getting latitude and longitude, we need to convert it into a real time address.
  1. get() {  
  2.     if (navigator.geolocation) {  
  3.         navigator.geolocation.getCurrentPosition((position: Position) => {  
  4.             if (position) {  
  5.                 this.lat = position.coords.latitude;  
  6.                 this.lng = position.coords.longitude;  
  7.                 this.getAddress = (this.lat, this.lng)  
  8.                 console.log(position)  
  9.                 this.apiloader.load().then(() => {  
  10.                     let geocoder = new google.maps.Geocoder;  
  11.                     let latlng = {  
  12.                         lat: this.lat,  
  13.                         lng: this.lng  
  14.                     };  
  15.                     geocoder.geocode({  
  16.                         'location': latlng  
  17.                     }, function(results) {  
  18.                         if (results[0]) {  
  19.                             this.currentLocation = results[0].formatted_address;  
  20.                             console.log(this.assgin);  
  21.                         } else {  
  22.                             console.log('Not found');  
  23.                         }  
  24.                     });  
  25.                 });  
  26.             }  
  27.         })  
  28.     }  
  29. }   
Step 12
 
In order to check the latitude and longitude, we need to call the method (Step 11) to ngOnInit to capture the address of that particular latitude and longitude.
  1. ngOnInit()  
  2.   {  
  3.     this.get()  
  4.     this.agmMap.triggerResize(true);  
  5.      this.zoom = 16;  
  6.     }  
Whats is ngOnInit?
 
It's called once the component is initialized.
 
Whats is Zoom?
 
Zoom customizes visibility. 
 
Step 13
 
Add the click event in your map and get the latitude and longitude address.
  1. mapClicked($event: MouseEvent) {  
  2.     this.latitude = $event.coords.lat,  
  3.         this.longitude = $event.coords.lng  
  4.     this.apiloader.load().then(() => {  
  5.         let geocoder = new google.maps.Geocoder;  
  6.         let latlng = {  
  7.             lat: this.latitude,  
  8.             lng: this.longitude  
  9.         };  
  10.         geocoder.geocode({  
  11.             'location': latlng  
  12.         }, function(results) {  
  13.             if (results[0]) {  
  14.                 this.currentLocation = results[0].formatted_address;  
  15.                 console.log(this.currentLocation);  
  16.             } else {  
  17.                 console.log('Not found');  
  18.             }  
  19.         });  
  20.     });  
  21. }  
Step 14
 
After completing all the above steps, we can run the project using the below command
 
Command - ng serve --open
 
Step 15
 
Now, the project will run successfully. In order to open the Project in the local browser, we need to provide the location permission in the browser.
 
Step 16
 
The app will open in your defalut browser.
 
Your projectis  running successfully.  The browser will ask for  location permission;  you can allow for this permission and after that you will see the map.
 
Get Current Location In Angular

Summary

 
I hope you understand how to add Google Maps in Angular Projects along with current location and map click events.
 
Any feedback or query related to this article is most welcome.