Integrate Google Map Places AutoComplete In Angular

In this blog, we will learn how to integrate Google Maps Places Autocomplete in Your Angular Application. Here we are integrating Autocomplete using typescript. We are going to load the Google Maps javascript in the app.component.tsfile. If you want to load it globally then you can load it in app.module.tsfile. but here we are going to load it in a particular component.

for doing any kind of interaction with the Google Maps API, we need an APIKEY from Google. Follow the link here to get APIKEY. After that, You need to replace YOUR_API_KEYwith your google map key.

If we were not using angular then we can just simply add a reference to javascript code by google in our HTML and specify the callback to be executed once the javascript file is loaded.

We can do it in our angular application by changing index.html but that will load google maps all over the application, but we want to load it in a particular activated component. so we will load the google maps javascript file dynamically.

Follow is the app.component.ts file.

import { Component, Inject, OnInit, Renderer2 } from '@angular/core';
import { NgForm } from '@angular/forms';
import { DOCUMENT } from '@angular/common';
declare const google;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  SearchPlacesForm: NgForm;
  public shippingAddress: string;

  constructor(@Inject(DOCUMENT) private document: Document, private renderer2: Renderer2) {

  }

  ngOnInit(): void {
    this.loadAutoComplete();
  }

  private loadAutoComplete() {
    const url = 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&v=weekly';
    this.loadScript(url).then(() => this.initAutocomplete());
  }

  private loadScript(url) {

    return new Promise((resolve, reject) => {
      const script = this.renderer2.createElement('script');
      script.type = 'text/javascript';
      script.src = url;
      script.text = ``;
      script.async = true;
      script.defer = true;
      script.onload = resolve;
      script.onerror = reject;
      this.renderer2.appendChild(this.document.head, script);
    })

  }

  initAutocomplete() {
    const input = document.getElementById("txtSearchPlaces") as HTMLInputElement;
    const autocomplete = new google.maps.places.Autocomplete(input);

    autocomplete.setFields([
      "address_components",
      "geometry",
      "icon",
      "name"
    ]);

    autocomplete.addListener("place_changed", () => {
      const place = autocomplete.getPlace();
      if (!place.geometry) {
        // User entered the name of a Place that was not suggested and
        // pressed the Enter key, or the Place Details request failed.
        alert('No details available for input:' + input.value);
        return;
      } else {
        return;
      }
    });

  }

}

in the above code, We called the loadAutoComplete() method under ngOnInit method.loadAutoComplete()will load/append the script with the given Google Map Javascript URL at the head of a document at the time of loading component. after successful load it will call initAutocomplete() method. it will initialize autocomplete in textbox which id we gave.

our app.component.html file will look like this

<div class="container" role="main">

  <div class="row">
    <div class="col-md-12">
      <h1>Google AutoComplete Demo</h1>
    </div>
  </div>

  <form class="form-horizontal" #SearchPlacesForm="ngForm">

    <div class="form-group">
      <label class="control-label col-sm-6" for="txtSearchPlaces">search places:</label>
      <div class="col-sm-6">
        <input type="text" class="form-control" id="txtSearchPlaces" name="txtSearchPlaces" #txtSearchPlaces="ngModel"
          [(ngModel)]="shippingAddress" placeholder="Enter places">
      </div>
    </div>

  </form>

</div>

<router-outlet></router-outlet>

in the above code, the text box which id is “txtSearchPlaces” will be initialized as Google Map AutoComplete. if you type any name of place then it will give you suggestion.

as we have added place_changed Listener, on entering or select place it will call that method and check if the place exists or not.

now just run the application and search for any places and it will suggest you places depend on your input.

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories