Wednesday, February 26, 2020

Ionic 4/5 Angular Google Maps With Places Search Using @Agm

Ionic 4/5 Angular Google Maps With Places Search Using @Agm
Create A New Ionic Application
To start from scratch we will create a new Ionic application with a blank template by running following NPM command in terminal:
$ ionic start ionic-agm-demo
? Starter template: blank
Install Packages To Use Google Maps
For using Angular Google Maps in the Ionic application we need to install @agm and Google Maps types by running the following commands:
Angular Google Maps
$ npm install @agm/core --save
Google Map Type
$ npm install @types/googlemaps --save-dev
Configurations
In the Ionic application, we need to import AgmCoreModule in the page’s module on which we are going to implement the Google maps.
So open home.module.ts file then import the AgmCoreModule package then add in the imports array as shown below with apiKey and 'places' set in libraries we want to use it.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';

import { HomePage } from './home.page';

import { AgmCoreModule } from '@agm/core';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild([
      {
        path: '',
        component: HomePage
      }
    ]),
    AgmCoreModule.forRoot({
      apiKey: 'YOUR_GOOGLE_API_KEY_HERE',
      libraries: ['places']
    })
  ],
  declarations: [HomePage]
})
export class HomePageModule {}
Next to define the Google Map type, open the tsconfig.app.json file then place "googlemaps" under types property:
...
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [
      "googlemaps"
    ]
  },
...
Adding Google Maps
Finally, we are going to add Maps to the Home page of the application.
In the home.page.html file paste below code:
<ion-header [translucent]="true">
  <ion-toolbar color="danger">
    <ion-title>
      Ionic Google Maps
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true" class="ion-padding">

    <input type="text" class="native-input sc-ion-input-ios" (keydown.enter)="$event.preventDefault()" placeholder="Search Nearest Location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" #search>

  <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>

</ion-content>
In the home.page.ts file update the component class wit below code:
import { Component, OnInit, ViewChild, ElementRef, NgZone } from '@angular/core';
import { MapsAPILoader, AgmMap } from '@agm/core';


@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage  implements OnInit {
  title: string = 'AGM project';
  latitude: number;
  longitude: number;
  zoom: number;
  address: string;
  private geoCoder;

  @ViewChild('search',{static:false})
  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, {
        types: ["address"]
      });
      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: any) {
    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);
      }

    });
  }

}
Ionic 4/5 Angular Google Maps With Places Search Using @Agm