, , ,

Ionic 4/5 Angular Google Maps with Places Search using @agm

In this tutorial, we will learn how to add Google Maps in an Ionic application using a powerful package @agm. The @agm package provides directive components to easily add Maps, Markers and Geometric shapes like Radius on Google Maps in Angular applications. Here we will use the power of this great package to implement Google…

By.

min read

In this tutorial, we will learn how to add Google Maps in an Ionic application using a powerful package @agm. The @agm package provides directive components to easily add Maps, Markers and Geometric shapes like Radius on Google Maps in Angular applications.

Here we will use the power of this great package to implement Google Maps with a Draggable Marker and Search bar for places in Ionic 5 application using Angular.

Let’s get started!

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.

// home.module.ts
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:

<!-- home.page.html -->
<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>

To create a Google map we use the agm-map component directive which takes several input properties and emits output events as well. But latitude, longitude and zoom are important ones.

The agm-marker directive will add a marker on the map which is set be draggable by setting [markerDraggable] to true, it also emits the dragEnd event to get current coodinates on map.

In the home.page.ts file update the component class wit below code:

// home.page.ts
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);
      }

    });
  }

}

 

Also Check:

Ionic 6 Google Map, Geocoder & Places Search, Draggable Marker Tutorial

Angular 13 Google Maps Integration with Markers, Info Windows Tutorial

 

That’s it now you have an Ionic Application loaded with Google Maps with awsome places search and Draggable marker to move it and fetching coordinates.

 

 

Leave a Reply

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