Explains all the steps required to implement Google Maps in Ionic 4 for Android by developing a simple application.

Implement Google Maps In Ionic 4 For Android
Implement Google Maps In Ionic 4 For Android
March 10, 2019

This post explains all the steps required to implement Google Maps in Ionic 4 for Android applications. The steps should be the same for other versions of Ionic.

It assumes that the user is familiar with the Google Developer Console and knows the basics of Ionic and Angular. You can follow our Hello Ionic and Deploy Ionic App On Android tutorials to learn the basics of Ionic. You can also follow How To Install Android SDK Tools On Windows and How To Install Android SDK Tools On Ubuntu to install Android SDK Tools and create the Simulator without using Android Studio.

Create Credentials

We need to create the credential specific for native Android applications in order to implement the Google Maps service. Log in to Google Cloud Platform and click on the Navigation Menu(Top left Menu Icon), hover on APIs & Services and click on Credentials Link as shown in Fig 1.

All Credentials

Fig 1

The above action shows All Credentials Page having a list of active credentials. Click on the Create Credentials Button and then click on API key as shown in Fig 2.

Create Credentials

Fig 2

It will show the newly created API key as shown in Fig 3. Copy the API key to configure the application for maps.

API Key

Fig 3

You can either continue using the key in unrestricted mode or follow the steps in the next section to use it in protected mode.

Protect the API Key - Key restrictions

It's a little bit complex to make the build with the application restriction. You may skip it for testing purpose and implement the same while going for production. Click on the RESTRICT KEY Link to imposes restrictions on the key to avoid unauthorized actions. Provide an appropriate name to the key and restrict it to Android native as shown in Fig 4.

Restrict Key

Fig 4

Restrict key usage to the specified Android apps by adding an item to the section - Restrict usage to your Android apps. It's mandatory in case you have opted to restrict the applications to Android apps as shown in the below-mentioned figure.

API Key Restrictions

Fig - API Key Restrictions

Use the keystore or keytool to generate the SHA-1 certificate fingerprint as highlighted in the Fig - API Key Restrictions. The command used by me is as shown below. I have run it at the project root directory.

# Goto project root
cd <project root path>

# Generate Release Key - Command
keytool -genkey -v -keystore release-key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias <alias>

# Generate Release Key - Example
keytool -genkey -v -keystore release-key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias vcdevhub

Make sure to replace vcdevhub with the alias used by you. It will ask a few questions as shown below.

Generate Key

Fig - Generate Key

After successfully generating the key, obtain the SHA1 Fingerprint using the below-mentioned command. Make sure to replace vcdevhub with the alias used by you.

# Get the SHA1 and SHA256 fingerprints
keytool -list -v -keystore release-key.jks -alias vcdevhub

Now copy the fingerprint and update the SHA-1 fingerprint within the section - Restrict usage to your Android apps on Google Cloud Platform and click on the DONE Button. This is how we can generate the key and update the SHA-1 certificate fingerprint.

Restrict Services

You can also restrict the key to access Android Maps services only as shown in Fig 5.

API Restriction

Fig 5

Again click on Navigation Menu -> APIs & Services -> Library to view all the available services. Search for Maps as shown in Fig 6.

Maps Services

Fig 6

Click on Maps SDK for Android and then click on the Enable Button to enable the maps service for Android native applications.

Create Maps Application

Create the Maps application following the steps mentioned in the Hello Ionic tutorial.

// Create the Maps application
ionic start maps blank

// Go to app directory
cd maps

// Configure Cordova by providing the API key
ionic cordova plugin add cordova-plugin-googlemaps --variable API_KEY_FOR_ANDROID="<Google Maps key for Android>"

// Install Google Maps NPM package
npm install @ionic-native/core @ionic-native/google-maps

The above-mentioned commands create the application having the name set to maps and configure Cordova google maps plugin to use the API key created by us. We have also installed the google maps component from Ionic.

Update Home

Open the file maps/src/app/home/home.page.html and update the content as shown below.

<ion-header>
  <ion-toolbar>
    <ion-title>
      Hello Maps
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div id="map" style="height:100%;"></div>
</ion-content>

The above lines add the title using the header tag and cover the entire content area to show the map.

Configure App

In this step, we will create and configure the app to use Google Maps from Ionic by using appropriate imports.

Open the file maps/src/app/home/home.page.ts and update the content as shown below.

import { Component, ViewChild } from '@angular/core';

// Import classes from maps module import { GoogleMaps, GoogleMap, GoogleMapsEvent, LatLng, MarkerOptions, Marker } from "@ionic-native/google-maps"; import { Platform, NavController } from "@ionic/angular"; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage {

constructor( public platform: Platform, public nav: NavController ) {

} }

Open the file maps/src/app/app.module.ts and update the content as shown below.

....
....
import { GoogleMaps } from '@ionic-native/google-maps';

@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
GoogleMaps
], .... ....

Update HomePage Class

Now we will update the HomePage Class to process the map as shown below.

....
....
export class HomePage {

constructor( public platform: Platform, public nav: NavController ) {

}

ngAfterViewInit() {

this.platform.ready().then( () => {

this.loadMap();
});
}

}

Now add the method loadMap as shown below to load the map using the map element added by us in the home.page.html view file.

loadMap() {

let map = GoogleMaps.create( 'map' );

map.one( GoogleMapsEvent.MAP_READY ).then( ( data: any ) => {

let coordinates: LatLng = new LatLng( 36.7783, 119.4179 );

let position = {
target: coordinates,
zoom: 14
};

map.animateCamera( position );

let markerOptions: MarkerOptions = {
position: coordinates,
icon: "assets/images/marker.png",
title: 'Hello California'
};

const marker = map.addMarker( markerOptions )
.then( ( marker: Marker ) => {
marker.showInfoWindow();
});
})
}

Configure Package Name

We have to provide unique Bundle Id also called as Package Id to uniquely identify the application in Play Store. It's usually reverse domain name in the case where a website is associated with the application.

Optional - Open the file maps\platforms\android\app\src\main\res\xml\config.xml and update the id with the Package Id. Replace the id io.ionic.starter with your Package Id.

Required - Update the same id in the application root file maps\config.xml replacing the auto-generated id io.ionic.starter.

Also, add the preference to the file maps\config.xml as shown below.

....
<preference name="GOOGLE_MAPS_ANDROID_API_KEY" value="<your key>" />
....

Build the Application

Build the application using build command as shown below. It will take some time to build the application for the first time.

ionic cordova build android

Run the Application - Without Application restrictions

Once the build completes successfully, simply run the application to deploy on android device as shown below in case you have not restricted the key to Android apps as shown in the previous section. Also, make sure that you have at least one active virtual or physical device available to run the application.

# Run on Android
ionic cordova run android

It will execute the application and show the map having the coordinates provided by us as shown in Fig 7.

App Output

Fig 7

Run the Application - With Application restrictions

It's a little bit complex as mentioned by me in the previous section while generating the key, but at the same time, it's the secure way to generate the build for production mode.

Build the application for production usage using the command as shown below.

# Build for production
ionic cordova build android --prod --release

# Permit jarsigner
sudo chmod 777 /<path to project>/platforms/android/app/build/outputs/apk/release

# Generate digital signature
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore release-key.jks platforms/android/app/build/outputs/apk/release/app-release-unsigned.apk <alias>
# Example
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore release-key.jks platforms/android/app/build/outputs/apk/release/app-release-unsigned.apk vcdevhub

Now move to your build tools used by cordova to build the apk.

# Install apksigner in case it's not done
sudo apt install apksigner

# Move to build-tools
cd /drivea/java/android/android-sdk/build-tools/28.0.3

# Align the release
./zipalign -v 1 <path to app>/platforms/android/app/build/outputs/apk/release/app-release-unsigned.apk <path to app>/platforms/android/app/build/outputs/apk/release/release-alinged.apk

# Sign the apk for release
apksigner sign --ks <path to app>/release-key.jks --out <path to app>/platforms/android/app/build/outputs/apk/release/final-release.apk <path to app>/platforms/android/app/build/outputs/apk/release/release-alinged.apk

This is how we can generate the apk for production usage. The apk can be deployed either to virtual machine or physical device to view the application output with Application restrictions.

Key Notes

These notes might be handy in case the default emulator without custom hardware profile does not work out of the box.

* Use the Google Play Services system images as mentioned in Deploy Ionic App On Android tutorial.

* Try to increase the Heap size.

* Use pre-configured hardware profile Nexus 5 or Nexus 5s configured with Play Store.

* Connect your device with the system and run the application instead of using AVD.

The complete source code is available on GitHub.

Write a Comment

Click on the captcha image to get new code.
Discussion Forum by DISQUS