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.
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”.
Step 3
Install the Google map reference npm using the following command.
Step 4
Open the tsconfig.app.json in your project and update the following reference code.
- {
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "./out-tsc/app",
- "types": ["googlemaps"]
- },
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.
- {
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "./out-tsc/spec",
- "types": [
- "jasmine",
- "node",
- "googlemaps"
- ]
- },
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:
- 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"
C) On the credentials page, open the "CREATE CREDENTIALS" and select the API key.
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.
- imports: [
- AgmCoreModule.forRoot({
- apiKey: 'Paste Your Api Key'
- }),
- ],
Step 8
Open the app.component.ts file which you can add in the agmmap reference file.
- import {AgmMap, MouseEvent,MapsAPILoader } from '@agm/core';
Step 9
A) After then we can declare the agmmap for view child.
- @ViewChild(AgmMap,{static: true}) public agmMap: AgmMap;
B) And assgin the mapsAPIloader in constructor.
- constructor(private apiloader: MapsAPILoader) {}
Step 10
Now, open app.component.html file & add the below code. Similarly, open the app.component.ts file.
- <form>
- <agm-map style="height: 300px;" [latitude]="lat" [longitude]="lng" [zoom]="zoom" (mapClick)="mapClicked($event)">
- <agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
- </agm-map>
- </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.
- get() {
- if (navigator.geolocation) {
- navigator.geolocation.getCurrentPosition((position: Position) => {
- if (position) {
- this.lat = position.coords.latitude;
- this.lng = position.coords.longitude;
- this.getAddress = (this.lat, this.lng)
- console.log(position)
- this.apiloader.load().then(() => {
- let geocoder = new google.maps.Geocoder;
- let latlng = {
- lat: this.lat,
- lng: this.lng
- };
- geocoder.geocode({
- 'location': latlng
- }, function(results) {
- if (results[0]) {
- this.currentLocation = results[0].formatted_address;
- console.log(this.assgin);
- } else {
- console.log('Not found');
- }
- });
- });
- }
- })
- }
- }
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.
- ngOnInit()
- {
- this.get()
- this.agmMap.triggerResize(true);
- this.zoom = 16;
- }
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.
- mapClicked($event: MouseEvent) {
- this.latitude = $event.coords.lat,
- this.longitude = $event.coords.lng
- this.apiloader.load().then(() => {
- let geocoder = new google.maps.Geocoder;
- let latlng = {
- lat: this.latitude,
- lng: this.longitude
- };
- geocoder.geocode({
- 'location': latlng
- }, function(results) {
- if (results[0]) {
- this.currentLocation = results[0].formatted_address;
- console.log(this.currentLocation);
- } else {
- console.log('Not found');
- }
- });
- });
- }
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.
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.