Ionic 4 Google Map — Part 4 — Direction Between Two Locations

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. Soi wants to import the ReactiveFormsModule into the imports section of your current module.

here the same code of my app.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;

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.

constructor(private fb: FormBuilder) {
}

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

createDirectionForm() {
this.directionForm = this.fb.group({
source: ['', Validators.required],
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: formValues.source,
destination: formValues.destination,
travelMode: 'DRIVING'
}, (response, status) => {
if (status === 'OK') {
that.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}

Here is the complete code of our app.component.ts file

import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
declare var google;
@Component({
selector: 'app-direction',
templateUrl: './direction.page.html',
styleUrls: ['./direction.page.scss'],
})
export class DirectionPage implements OnInit, AfterViewInit {
@ViewChild('mapElement') mapNativeElement: ElementRef;
directionsService = new google.maps.DirectionsService;
directionsDisplay = new google.maps.DirectionsRenderer;
directionForm: FormGroup;
constructor(private fb: FormBuilder) {
this.createDirectionForm();
}
  ngOnInit() {
}
  createDirectionForm() {
this.directionForm = this.fb.group({
source: ['', Validators.required],
destination: ['', Validators.required]
});
}
  ngAfterViewInit(): void {
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: formValues.source,
destination: formValues.destination,
travelMode: 'DRIVING'
}, (response, status) => {
if (status === 'OK') {
that.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
}

Here is the complete code of your app.component.html file

<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>Direction</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
  <form [formGroup]="directionForm" (ngSubmit)="calculateAndDisplayRoute(directionForm.value)">
<ion-item>
<ion-label position="floating">Source</ion-label>
<ion-input formControlName="source"></ion-input>
</ion-item>
<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.invalid">Get Direction</ion-button>
</form>
  <div #mapElement class="map"></div>
</ion-content>

This is the result.

For more Tutorials visit https://ramsatt.com