Open In App

How to Add Google Locations Autocomplete to your Angular Application ?

The task here is to Add Google Locations Autocomplete to your Angular Application. When user will enter some text for a location in the Textfield, he/she will get locations recommendations and can autocomplete the location. For achieving the target, we will use ngx-google-places-autocomplete angular package.

What is ngx-google-places-autocomplete ?

This module is a wrapper for Google Places Autocomplete js library. It allows us to integrate locations autocomplete to our project.



Approach

For npm:

npm install ngx-google-places-autocomplete

For yarn:



yarn add ngx-google-places-autocomplete

<script src=”https://maps.googleapis.com/maps/api/js?key=<Your API KEY>&libraries=places&language=en”></script>

import { GooglePlaceModule } from "ngx-google-places-autocomplete";

@NgModule({

  imports: [
    GooglePlaceModule
  ],

Note: In country Array there is “AU” added for Australia, you can add any other country according to you. 

Implementation:

app.module.ts




import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import '@angular/compiler';
//import for GooglePlaceModule
import { GooglePlaceModule } from "ngx-google-places-autocomplete";
  
@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    //Adding to imports
    GooglePlaceModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html




<div class="container">
    <h1>GeeksforGeeks</h1>
    <h2>Google Places Autocomplete</h2>
<input ngx-google-places-autocomplete [options]=
   'options'  (onAddressChange)="AddressChange($event)"/>
{{ formattedaddress }}
</div>

app.component.ts




import { Component } from '@angular/core';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'rou';
  //Local Variable defined
  formattedaddress=" ";
  options={
    componentRestrictions:{
      country:["AU"]
    }
  }
  public AddressChange(address: any) {
  //setting address from API to local variable
   this.formattedaddress=address.formatted_address
}
}

Output:

Run development server using ng serve and write some location to input field to see Autocomplete locations.


Article Tags :