Angular

Integrate Google Maps In Angular

In this article, we will learn how to integrate Google Maps into our Angular Application. Here we are integrating Google Maps using typescript. We are going to load the Google Maps javascript in the app.component.ts file. If you want to load it globally then you can load it in app.module.ts file. but here we are going to load it in a particular component.

We are also integrating Google Map Places Auto Complete for suggestions of places. so whenever the user types in the text box it will suggest places according to your typing. here is the link to Integrate Google Map Places AutoComplete In Angular.

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_KEY with 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 {
  SearchPlacesForm: NgForm;
  public shippingAddress: string;

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

  }

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

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

  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);
    })

  }

  initMap() {

    const map = new google.maps.Map(this.document.getElementById("map") as HTMLInputElement, {
      center: {
        lat: 21.2046704,
        lng: 72.8358745
      },
      zoom: 13
    });

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

    autocomplete.bindTo("bounds", map); // Set the data fields to return when the user selects a place.

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

    const infowindow = new google.maps.InfoWindow();
    const infowindowContent = this.document.getElementById("infowindow-content") as HTMLInputElement;
    infowindow.setContent(infowindowContent);
    const marker = new google.maps.Marker({
      map,
      anchorPoint: new google.maps.Point(0, -29)
    });

    autocomplete.addListener("place_changed", () => {
      infowindow.close();
      marker.setVisible(false);
      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;
      } // If the place has a geometry, then present it on a map.

      if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
      } else {
        map.setCenter(place.geometry.location);
        map.setZoom(17);
      }

      marker.setPosition(place.geometry.location);
      marker.setVisible(true);
      let address = "";

      if (place.address_components) {
        address = [
          (place.address_components[0] &&
            place.address_components[0].short_name) ||
          "",
          (place.address_components[1] &&
            place.address_components[1].short_name) ||
          "",
          (place.address_components[2] &&
            place.address_components[2].short_name) ||
          ""
        ].join(" ");
      }

      infowindowContent.children["place-icon"].src = place.icon;
      infowindowContent.children["place-name"].textContent = place.name;
      infowindowContent.children["place-address"].textContent = address;
      infowindow.open(map, marker);

    });

  }


}

in the above code, We called the loadMap() method under ngOnInit method.loadMap()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 initMap() method. it will initialize Google Map in DIV which id we gave and autocomplete in textbox which id we gave. also it binds autocomplete with maps so when the user selects place it will show in the map.

our app.component.html file will look like this

<style type="text/css">
  #map {
    height: 100vh;
    border-style: solid;
  }

  #infowindow-content .title {
    font-weight: bold;
  }

  #infowindow-content {
    display: none;
  }

  #map #infowindow-content {
    display: inline;
  }

</style>

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

  <div class="row">
    <div class="col-md-12">
      <h1>Google Maps 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 class="row">
    <div class="col-md-12 my-4">
      <div id="map"></div>
      <div id="infowindow-content">
        <img src="" width="16" height="16" id="place-icon" />
        <span id="place-name" class="title"></span><br />
        <span id="place-address"></span>
      </div>
    </div>
  </div>

</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. also, DIV which Id is a “map” will be initialized as Google Map. it will display the location in the map which place we type in the text box.

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. if the place exists then it will show it on the map and if the place does not exist then it will show an alert message.

now run the application and search for any places and it will suggest you places just click on the place and you will see that place in Google Map.

 

Tabish Rangrej

Tabish Rangrej is an Experienced .NET Team Leader, software engineer, and Author with a demonstrated history of working in the IT industry. He has quite well experience in developing, communicating, managing, and writing in his field. He has strong skills and knowledge of ASP.NET C#, ASP.NET MVC, ASP.NET CORE, Angular, AngularJS, Web API, SQL, Entity Framework, JavaScript, Jquery, Different Integrations like Quickbooks, Stripe, Google APIs, Zoho, Orion, Xero, etc., Different versioning tools like TFS, SVN, GIT, etc. and Windows services. Strong engineering professional with a Master of Computer Applications - MCA focused on Computer Science from Veer Narmad South Gujarat University, Surat. Tabish is always ready to accept new challenges and learn new things, he would like to serve better for the community.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago