In this article, we are going to learn how to build an Angular 12 application with Google Places Autocomplete.
Google Places Autocomplete lets the user search for an address or a specific location and also get latitude, longitude, and other information about the location.
Let’s get started,
Step 1
Create a new Angular 12 Project. Use the following command.
ng new google-places-autocomplete
Step 2
Install ngx-google-places-autocomplete package using the node package manager NPM
npm install ngx-google-places-autocomplete
Step 3
Add Google API key in index.html with your own key.
To generate the API Key go to https://developers.google.com/places/web-service/get-api-key and follow the instruction.
<script src="https://maps.googleapis.com/maps/api/js?key=<YOUR_API_KEY_HERE>&libraries=places&language=en"></script>
Step 4
Import GooglePlacesModule in the app.module.ts,
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { GooglePlaceModule } from 'ngx-google-places-autocomplete';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
GooglePlaceModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Step 5
Add the below code in your HTML file. In my case, I haven't made any different components so I have added app.component.html.
<div class="container">
<input ngx-google-places-autocomplete (onAddressChange)="handleAddressChange($event)" />
<p>Address: {{ userAddress }}</p>
<p>Latitude: {{ userLatitude }}</p>
<p>Longitude: {{ userLongitude }}</p>
</div>
Step 6
Add the below code in the TS file. In my case, I haven't made any different components so I have added in app.component.ts.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'google-places-autocomplete';
userAddress: string = ''
userLatitude: string = ''
userLongitude: string = ''
handleAddressChange(address: any) {
this.userAddress = address.formatted_address
this.userLatitude = address.geometry.location.lat()
this.userLongitude = address.geometry.location.lng()
}
}
In the above code, we are fetching the address using the onAddressChange method of GooglePlacesAutoComplete Package. We will get formatted address, latitude, and longitude from the address object return by the onAddressChange method.
I hope this will help you. Thanks