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.
- import {
- AgmCoreModule
- } from '@agm/core ';
- @NgModule({
- imports: [
- AgmCoreModule.forRoot({
- apiKey: 'Your Google Api Key'
- })
- ],
- })
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.
- import {
- Component,
- ViewChild,
- ElementRef,
- OnInit,
- Pipe,
- PipeTransform,
- ChangeDetectorRef
- } from '@angular/core';
- import {
- AgmCoreModule,
- AgmMap
- } from '@agm/core';
- @ViewChild(AgmMap) public agmMap: AgmMap;
- public lat: number;
- public lng: number;
- zoom: number;
- ngOnInit() {
- this.lat = 51.673858;
- this.lng = 7.815982;
- this.zoom = 16;
- this.agmMap.ngOnDestroy();
- this.agmMap.triggerResize(true);
- }
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.
- <agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom" [streetView]="true" [scrollwheel]="true" [zoomControl]="true">
- <agm-marker [latitude]="lat" [longitude]="lng"> </agm-marker>
- </agm-map>
Finally, I got the exact position from Google Maps. I hope this blog is helpful for you.