In this article, I want to explain how to implement direction services inside an ionic 4 application using google map javascript API.

In this tutorial, I am using google map direction API. you must enable the direction service on your Google cloud API console. Otherwise, it’s not working. So please make sue direction services must be enabled in your API console.

In this sample, I am using reactive forms for getting the source and destination location from the user as an input. So i wants to import the ReactiveFormsModule into the imports section of your current module.

here the same code of my home.module.ts file.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';

import { IonicModule } from '@ionic/angular';

import { DirectionPage } from './direction.page';

const routes: Routes = [
  {
    path: '',
    component: DirectionPage
  }
];

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild(routes),
    ReactiveFormsModule
  ],
  declarations: [DirectionPage]
})
export class DirectionPageModule {}

Declare a global variable for google. Use the following code to do that.

declare var google;

Create the following class level variable to implement the direction services.

@ViewChild('mapElement') mapNativeElement: ElementRef;
directionsService = new google.maps.DirectionsService;
directionsDisplay = new google.maps.DirectionsRenderer;
directionForm: FormGroup;
currentLocation: any = {
  lat: 0,
  lng: 0
};

The first one is used for accessing the template tag into your component class. So, we use the ViewChild element here.

@ViewChild('mapElement') mapNativeElement: ElementRef;

directionsService used to implement the google map direction services into our application. It communicates to the google map server and gets the direction response. directionsDisplay is used to render the direction path into our application. directionForm is used to create a reactive form to get locations from user. currentLocation is used to stored the Geo locations coordinates

constructor(private fb: FormBuilder) {
}

import the FormBuilder into the component class using DI.(Dependancy Injection)

createDirectionForm() {
  this.directionForm = this.fb.group({
    destination: ['', Validators.required]
  });
}

This function used to initialize the form into your component class. After creating this you must call this function into constructor.

constructor(private fb: FormBuilder) {
this.createDirectionForm();
}

Next, create a google map into the ngAfterViewInit section like the follow

ngAfterViewInit(): void {
const map = new google.maps.Map(this.mapNativeElement.nativeElement, {
zoom: 7,
center: {lat: 41.85, lng: -87.65}
});
this.directionsDisplay.setMap(map);
}

Create a method for calculate the direction between two location.

calculateAndDisplayRoute(formValues) {
const that = this;
this.directionsService.route({
origin: this.currentLocation,
destination: formValues.destination,
travelMode: 'DRIVING'
}, (response, status) => {
if (status === 'OK') {
that.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}

Here i pass the source and destination values.

The complete code of home.component.ts file

import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Geolocation} from '@ionic-native/geolocation/ngx';
declare var google;
@Component({
selector: 'app-direction-geo',
templateUrl: './direction-geo.page.html',
styleUrls: ['./direction-geo.page.scss'],
})
export class DirectionGeoPage implements OnInit, AfterViewInit {
@ViewChild('mapElement') mapNativeElement: ElementRef;
directionsService = new google.maps.DirectionsService;
directionsDisplay = new google.maps.DirectionsRenderer;
directionForm: FormGroup;
currentLocation: any = {
lat: 0,
lng: 0
};
constructor(private fb: FormBuilder, private geolocation: Geolocation) {
this.createDirectionForm();
}

ngOnInit() {
}

createDirectionForm() {
this.directionForm = this.fb.group({
destination: ['', Validators.required]
});
}

ngAfterViewInit(): void {
this.geolocation.getCurrentPosition().then((resp) => {
this.currentLocation.lat = resp.coords.latitude;
this.currentLocation.lng = resp.coords.longitude;
});
const map = new google.maps.Map(this.mapNativeElement.nativeElement, {
zoom: 7,
center: {lat: 41.85, lng: -87.65}
});
this.directionsDisplay.setMap(map);
}

calculateAndDisplayRoute(formValues) {
const that = this;
this.directionsService.route({
origin: this.currentLocation,
destination: formValues.destination,
travelMode: 'DRIVING'
}, (response, status) => {
if (status === 'OK') {
that.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}

}

and your home.component.html file like to be

<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>Direction with GeoLocation</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>

<form [formGroup]="directionForm" (ngSubmit)="calculateAndDisplayRoute(directionForm.value)">
<ion-item>
<ion-label position="floating">Destination</ion-label>
<ion-input formControlName="destination"></ion-input>
</ion-item>
<ion-button expand="full" type="submit" [disabled]="!directionForm.valid">Get Direction</ion-button>
</form>

<div #mapElement class="map"></div>
</ion-content>

1 COMMENT