Google Maps JavaScript API, Geolocation, Geocoder in Ionic Native Application for Ionic 5|4

Vasanth Kumar
6 min readApr 18, 2021

--

Ionic 5 tutorial, we’ll implement Google Maps using Javascript API library and display current position with a location marker and address of the location. To build Google Maps in Ionic 5 application we’ll use Geolocation and plugins to locate current coordinates and address

how to get location coordinates using Geolocation and then converting those coordinates into understandable addresses using Geocoder plugin without Google Maps. But adding a map in a mobile application adds much value making it more useful and interactive.

We’ll implement Google Maps in Ionic Application, user can drag or zoom maps and get Coordinates and Address location marker position. To achieve this we’ll use Google’s Javascript API library with Ionic Geolocation and Geocoder Native plugins to fetch device location then fetch Address available for those coordinates we get.

Here I am going to create an Ionic Application with Google Maps, having a location pointer in the centre of the map, a user can drag, pan or zoom map to get an address at that location.

We are going to create Ionic Application in latest version 5, it is still in beta phase but soon it will be available as a stable version. But all steps will remain almost the same.

Let’s get started!

Create a new Ionic 5 Application

Setup a new Ionic 5 Angular application with a template by using below ionic command

$ ionic start ionic-geolocation-geocoder-application blank --type=angular$ cd ionic-geolocation-geocoder-application

Add Google Maps API in Ionic Application

We’ll include Google Maps API link in the header section of our Ionic application. A few months back the Google Maps JavaScript API has made the use of API Key mandatory only after adding the key it can be used in web applications. To know more on how to get API Key to visit this link.

Now open index.html at the root of your Ionic Application, then add the script tag with your key in the head section as shown below:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8" />
<title>Ionic App</title>

<base href="/" />

<meta name="color-scheme" content="light dark" />
<meta name="viewport"
content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />

<link rel="icon" type="image/png" href="assets/icon/favicon.png" />

<!-- add to homescreen for ios -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />

<script src="https://maps.google.com/maps/api/js?key=YOUR_KEY"></script>
</head>

<body>
<app-root></app-root>
</body>

</html>

Install Geolocation and Geocoder Cordova and Ionic Native plugins

Now we’ll install required Cordova plugins with Ionic Native wrappers to use these plugins in an Angular application. We’ll be using the Geolocation and Geocoder plugins for our application.

The Geolocation plugin will fetch coordinates of the device in the form of latitude and longitude, after that we will convert these coordinates in addresses using Geocoder plugin.

Run the following commands to install these plugins.

Geolocation

The Geolocation plugin will fetch Native device location coordinates including latitude, longitude, time, accuracy etc.

$ ionic cordova plugin add cordova-plugin-geolocation
$ npm install @ionic-native/geolocation

Import Plugins in Application Module.

To use Geolocation and Geocoder services in our components, we’ll need to import Geolocation and NativeGeocoder then add in the providers array in the app.module.ts file as shown below:

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { Geolocation } from '@ionic-native/geolocation/ngx';
import { NativeGeocoder } from '@ionic-native/native-geocoder/ngx';

@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
StatusBar,
SplashScreen,

Geolocation,
NativeGeocoder,

{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule { }

Adding Google Map in Homepage

Home Page Template HTML

To show Google maps in the homepage we need to add a placeholder for the map in which we will load Google Map. A div element with having template reference variable #map will act as a wrapper to load Google Maps.

An /img tag with an icon to point current location in maps.

<div class="map-wrapper">
<div id="map_center">
<img src="assets/icon/location-marker.png" />
</div>
<div #map id="map"></div>
</div>

There is a ion-grid section to display the coordinates including latitude and longitude, also the address converted by using the Geocoder plugin.

In the header section, there will be a button to move maps to the current location of the device.

<!-- home.page.html -->
<ion-header [translucent]="true">

<ion-toolbar color="warning">
<ion-button (click)="loadMap()" shape="round" color="dark">
<ion-icon slot="start" name="locate"></ion-icon>
Where I Am
</ion-button>
<ion-title slot="end">Google Map</ion-title>
</ion-toolbar>

</ion-header>

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

<div class="map-wrapper">
<div id="map_center">
<img src="assets/icon/location-marker.png" />
</div>
<div #map id="map"></div>
</div>

<ion-grid>
<ion-row>
<ion-col size="3">
<b>Lattitude</b>
</ion-col>
<ion-col>
{{latitude}}
</ion-col>
</ion-row>
<ion-row>
<ion-col size="3">
<b>Longitude</b>
</ion-col>
<ion-col>
{{longitude}}
</ion-col>
</ion-row>
<ion-row>
<ion-col size="3">
<b>Address</b>
</ion-col>
<ion-col>
{{address}}
</ion-col>
</ion-row>
</ion-grid>


</ion-content>

Home Component Class

Now we will modify the home component file to load Google maps. Replace the following code in

// home.page.ts
import { Component, ViewChild, ElementRef } from '@angular/core';

import { Geolocation } from '@ionic-native/geolocation/ngx';
import { NativeGeocoder, NativeGeocoderResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder/ngx';

declare var google;

@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {

@ViewChild('map', { static: false }) mapElement: ElementRef;
map: any;
address: string;

latitude: number;
longitude: number;

constructor(
private geolocation: Geolocation,
private nativeGeocoder: NativeGeocoder) {
}


ngOnInit() {
this.loadMap();
}

loadMap() {
this.geolocation.getCurrentPosition().then((resp) => {

this.latitude = resp.coords.latitude;
this.longitude = resp.coords.longitude;

let latLng = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}

this.getAddressFromCoords(resp.coords.latitude, resp.coords.longitude);

this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);

this.map.addListener('dragend', () => {

this.latitude = this.map.center.lat();
this.longitude = this.map.center.lng();

this.getAddressFromCoords(this.map.center.lat(), this.map.center.lng())
});

}).catch((error) => {
console.log('Error getting location', error);
});
}

getAddressFromCoords(lattitude, longitude) {
console.log("getAddressFromCoords " + lattitude + " " + longitude);
let options: NativeGeocoderOptions = {
useLocale: true,
maxResults: 5
};

this.nativeGeocoder.reverseGeocode(lattitude, longitude, options)
.then((result: NativeGeocoderResult[]) => {
this.address = "";
let responseAddress = [];
for (let [key, value] of Object.entries(result[0])) {
if (value.length > 0)
responseAddress.push(value);

}
responseAddress.reverse();
for (let value of responseAddress) {
this.address += value + ", ";
}
this.address = this.address.slice(0, -2);
})
.catch((error: any) => {
this.address = "Address Not Available!";
});

}

}

Here we will call loadMap() method which in turn call getCurrentPosition() method to get current location coordinates to load Google Maps with centre location set to Latitude and Longitude received in Geolocation method.

The getAddressFromCoords() the method will get Lattitude and Longitude values to return Addresses available using Geocoder’s method, in this method I have added some JS login to create comma separated address from JSON object of address.

Here I have added map’s event listener dragend to get coordinates on Google Map Center to find an address. This event is fired when the user stops the dragged map.

Style the Map

In the home.page.scss file, add following CSS style for centre pointer mark, map container height and address styling

#map_canvas {
width: 90%;
height: 80%;
border: 1px solid red;
}


#address {
padding: 10px;
font-size: 18px;
font-weight: bold;
}

#map {
width: 100%;
height: 70vh;
}

.map-wrapper {
position: relative;

#map_center {
position: absolute;
z-index: 99;
height: 40px;
width: 40px;
top: 50%;
left: 50%;
margin-left: -21px;
margin-top: -41px;
}
}

We are done with implementation. Now you need to run this application in the real device or emulator as the Geocoder service will only work with Cordova.

Thank you Guys.

--

--

Vasanth Kumar
Vasanth Kumar

Written by Vasanth Kumar

Software Developer seeking to leverage 4+ years of experience in Spark, SQL, AWS, Python,DataBricks and Front — end apps

No responses yet