Angular 8|9|10|11 Google map API integration with Angular Google Maps(AGM), we will learn how to implement Google map in angular 11 application, for google map we will use Angular Google Maps(AGM) package to embed a map in the Angular application
Angular 8|9|10|11 Google map API integration Example
- Step 1 – Create a new Angular 11 app
- Step 2 – Install agm/core NPM Package
- Step 3 – Import AgmCoreModule in AppModule
- Step 4 – Add code in the component file
- Step 5 – Add code in the view file
- Step 6 – Run an Angular 11 application
Step 1 – Create a new Angular 11 app
First of all, open your terminal and execute the following command to create a new Angular 11 app
ng new my-new-app
Step 2 – Install agm/core NPM Package
In this step, We will install agm/core NPM package to use google maps in angular application so open your terminal and run below for install AGM NPM module
npm install @agm/core --save
We also needs to install one dependency library, “@types/googlemaps” is required for support Typescript type definitions for the Google Maps Javascript API
Run below command for install “@types/googlemaps” dependency
npm install --save @types/googlemaps
Now, open the tsconfig.app.json file from the root folder, and add “googlemaps” in types array as like bellow
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": [
"googlemaps"
]
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}
Step 3 – Import AgmCoreModule in AppModule
Open the app.module.ts file and import AgmCoreModule from @agm/core in declaration part and update the import array
in this section, we must define the Google Map API Key for use google map, you can create a Google API key for Google Console, After generating the google key you need to define the key under apiKey property
One more thing, We are also using Places API for search location so enable Places API from API Library
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule } from '@angular/forms';
import { AgmCoreModule } from '@agm/core';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
AppRoutingModule,
AgmCoreModule.forRoot({
apiKey: 'API-KEY',
libraries: ['places']
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Step 4 – Add code in the component file
In this step, open the src/app/app.component.ts file and update the below code, i will explain the code later on this article
import { Component, OnInit, ViewChild, ElementRef, NgZone } from '@angular/core';
import { MapsAPILoader } from '@agm/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title: string = 'Google Map Integration';
latitude: number = 0;
longitude: number = 0;
zoom: number = 1;
address: string = '';
private geoCoder:any;
@ViewChild('search')
public searchRef: ElementRef;
constructor(
private mapsAPILoader: MapsAPILoader,
private ngZone: NgZone
) { }
ngOnInit() {
this.mapsAPILoader.load().then(() => {
this.setCurrentLocation();
this.geoCoder = new google.maps.Geocoder;
let autocomplete = new google.maps.places.Autocomplete(this.searchRef.nativeElement);
autocomplete.addListener("place_changed", () => {
this.ngZone.run(() => {
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
if (place.geometry === undefined || place.geometry === null) {
return;
}
this.latitude = place.geometry.location.lat();
this.longitude = place.geometry.location.lng();
this.zoom = 10;
});
});
});
}
private setCurrentLocation() {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
this.zoom = 8;
this.getAddress(this.latitude, this.longitude);
});
}
}
getAddress(latitude:number, longitude:number) {
this.geoCoder.geocode({ 'location': { lat: latitude, lng: longitude } }, (results:any, status:any) => {
if (status === 'OK') {
if (results[0]) {
this.zoom = 12;
this.address = results[0].formatted_address;
} else {
window.alert('Not found');
}
}
});
}
}
In ngOnInit method, setCurrentLocation() method will get the current location and set latitude and longitude to google map
you can also change the zoom level of google map, google map support the zoom level 0 to 22 level on the road map, levels may be different in the different type map
After that we have called the Google Autocomplete method to fetch the results, place_changed event will fire when the user selects a query
Step 5 – Add code in the view file
Update below code in src/app/app.component.html view file
<div class="map container">
<h1>Angular 11 AGM Integration Example</h1>
<div class="form-group">
<label>Enter address</label>
<input type="text" class="form-control" (keydown.enter)="$event.preventDefault()" placeholder="Search Nearest Location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" #search>
</div>
<agm-map [latitude]="latitude" [longitude]="longitude" [zoom]="zoom">
<agm-marker [latitude]="latitude" [longitude]="longitude" [markerDraggable]="true"
></agm-marker>
</agm-map>
<h5>Address: {{address}}</h5>
<div>Latitude: {{latitude}}</div>
<div>Longitude: {{longitude}}</div>
</div>
Step 6 – Run an Angular 11 application
Execute the following command on terminal run angular app
ng serve
Related Post
- How to use material chips(tags) in Angular?
- How to implement material spinner in Angular?
- Angular 12 autocomplete with API Data
- Angular 12 TinyMCE integration with an example
- Angular 12 Material Tabs Tutorial with Example
- Angular 12 Material Autocomplete Example
- Angular 12 Material Dialog Example
- How to bind HTML inside the angular binding?
- Angular 12 Bootstrap Responsive Carousel slider
- Angular 12 modal popup example with Bootstrap 4