How To Use Google Maps In Your Angular Application | Devstringx Technologies
Implementing google maps in your angular application may be interesting in the event that you don’t realize accurate stream however following these straightforward strides for executing maps anybody can implement it easily
Create a new angular project :-
ng new google-maps
Run Project :-
ng serve -o
Install google maps:-
To use google maps in your angular application, install @agm/core package
Run the following command to install AGM package
npm install @agm/core -save
Install Types for google maps:-
Next, we will install GoogleMaps types library
npm install @types/googlemaps -save-dev
Next, open the tsconfig.app.json already available in root,now add “GoogleMaps” in types array as show :-
{
“extends”: “../tsconfig.json”,
“compilerOptions”: {
“outDir”: “../out-tsc/app”,
“types”: [
“googlemaps”
]
},
“exclude”: [
“test.ts”,
“**/*.spec.ts”
]
}
Update the App Module:-
Next,open the app.module.ts file, import AgmCoreModule then update the imports array
import { BrowserModule } from ‘@angular/platform-browser’;
import { NgModule } from ‘@angular/core’;
import { AppComponent } from ‘./app.component’;
import { AgmCoreModule } from ‘@agm/core’;
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AgmCoreModule.forRoot({
apiKey: ‘YOUR-API-KEY-HERE’,
libraries: [‘places’]
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
During the import of AgmCoreModule we need to define our Google Console API key under apikey property.Also,you have to enabled the ‘places’ library to make search of places.
Getting Google Api Key:-
Go to the GoogleConsole .You need to signup/ signing with your Google credentials.
https://console.developers.google.com/
On going to above link you could get the google api key all the steps are mentioned on this site.
Adding Google Maps In Component:-
For creating google maps in template, we need to add <agm-maps/> component with binding properties for setting latitude,longitude,zoom etc.
The map will also have a marker, which is created by adding <agm-marker/> component
<!- app.component.html ->
<agm-map
[latitude]=”latitude”
[longitude]=”longitude”
[zoom]=”zoom” >
<agm-marker
[latitude]=”latitude”
[longitude]=”longitude”>
</agm-marker>
</agm-map>
Add this to your template to show the basic map in your application.
Add map height in app.component.css
agm–map
{
height: 300px;
}
Updating the component class:-
Geocoder location service will return address based on provided latitude, longitude in the method getAddress()
The template reference variable #search on input field is used to find the key events for fetching addresses based on current location
The markerDragEnd() after user stops marker drag to fetch the address of the current location
<!- app.component.html ->
<div class=”container”>
<h1>Angular Google Maps with Places Search 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”
(dragEnd)=”markerDragEnd($event)”></agm-marker>
</agm-map>
<h5>Address: {{address}}</h5>
<div>Latitude: {{latitude}}</div>
<div>Longitude: {{longitude}}</div>
</div>
//app.component.ts
import { Component, OnInit, ViewChild, ElementRef, NgZone } from ‘@angular/core’;
import { MapsAPILoader, MouseEvent } from ‘@agm/core’;
@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent implements OnInit {
title: string = ‘AGM project’;
latitude: number;
longitude: number;
zoom: number;
address: string;
private geoCoder;
@ViewChild(‘search’)
public searchElementRef: ElementRef;
constructor(
private mapsAPILoader: MapsAPILoader,
private ngZone: NgZone
) { }
ngOnInit() { //load Places Autocomplete
this.mapsAPILoader.load().then(() => {
this.setCurrentLocation();
this.geoCoder = new google.maps.Geocoder;
let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement);
autocomplete.addListener(“place_changed”, () => {
this.ngZone.run(() => {
//get the place result
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
//verify result
if (place.geometry === undefined || place.geometry === null) {
return;
}
//set latitude, longitude and zoom
this.latitude = place.geometry.location.lat();
this.longitude = place.geometry.location.lng();
this.zoom = 12;
});
});
});
}
// Get Current Location Coordinates
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);
});
}
}
markerDragEnd($event: MouseEvent) {
console.log($event);
this.latitude = $event.coords.lat;
this.longitude = $event.coords.lng;
this.getAddress(this.latitude, this.longitude);
}
getAddress(latitude, longitude) {
this.geoCoder.geocode({ ‘location’: { lat: latitude, lng: longitude } }, (results, status) => {
console.log(results);
console.log(status);
if (status === ‘OK’) {
if (results[0]) {
this.zoom = 12;
this.address = results[0].formatted_address;
} else {
window.alert(‘No results found’);
}
} else {
window.alert(‘Geocoder failed due to: ‘ + status);
}
});
}
}
Counted among the best Angular development services offering company in India by Clutch and Good firms, we provide full-cycle development services to our esteemed customers. Visit our angular development service page to learn more.
Originally published at https://www.devstringx.com on February 22, 2021.