, , , ,

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

In this 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 Geocoder plugins to locate current coordinates and address. In the previous post, we discussed how to get…

By.

•

min read

In this 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 Geocoder plugins to locate current coordinates and address.

In the previous post, we discussed 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!

Also Check: Ionic 4 | Turn on Device GPS in Ionic 4 Application Without Leaving App

 

Version Check

@ionic/cli 

   _             _
  (_) ___  _ __ (_) ___
  | |/ _ \| '_ \| |/ __|
  | | (_) | | | | | (__
  |_|\___/|_| |_|_|\___| CLI 6.4.1


#Update to the latest version of Ionic CLI by running following NPM command:

$ npm install -g @ionic/cli

 

First, we will start on a new project.

# Create a new Ionic 5 Application

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

$ ionic start ionic-geolocation-geocoder-application blank --type=angular</pre>
Move to the application folder
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ cd ionic-geolocation-geocoder-application</pre>
 
<h3># Add Google Maps API in Ionic Application</h3>
We'll include Google Maps API link in the header section of our Ionic application. A few months back the Google Maps <a href="https://developers.google.com/maps/documentation/javascript/tutorial" target="_blank" rel="noopener noreferrer">JavaScript API</a> 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 <a href="https://developers.google.com/maps/documentation/javascript/get-api-key" target="_blank" rel="noopener noreferrer">this</a> link.

Now open <strong>index.html</strong> at the root of your Ionic Application, then add the script tag with your key in the head section as shown below:
<pre class="lang:xhtml mark:22 decode:true"><!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></pre>
<h4></h4>
<h3># Install Geolocation and Geocoder Cordova and Ionic Native plugins</h3>
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.
<h3><strong>Geolocation</strong></h3>
The Geolocation plugin will fetch Native device location coordinates including latitude, longitude, time, accuracy etc.
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ ionic cordova plugin add cordova-plugin-geolocation
$ npm install @ionic-native/geolocation</pre>
 
<h3><strong>Geocoder</strong></h3>
The Geocoder plugin will fetch address and places when a specific coordinate is passed.
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ ionic cordova plugin add cordova-plugin-nativegeocoder
$ npm install @ionic-native/native-geocoder</pre>
<h4></h4>
<h3># Import Plugins in Application Module.</h3>
To use Geolocation and Geocoder services in our components, we'll need to import <code>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 id='map' 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></pre>
There is a <code>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 file.

// 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.

# How to build the Ionic 5 application?

You first need to add a platform for the Ionic application by running below ionic command

$ ionic cordova platform add android

Now build APK file by running

$ ionic cordova build android

Or you can run the application directly in the USB connected device to your PC by running

$ ionic cordova run android -l

 

Get source code in GitHub repo here

Conclusion: So here we discussed how to add Google maps in the Ionic 5 application and get current coordinated using the Geolocation plugin and also convert the coordinates into readable address using the Geocoder plugin. Also discussed how to build and run the application in a real device.

 

21 responses to “Ionic 5|4 Google Maps JavaScript API, Geolocation, Geocoder in Ionic Native Application”

  1. Ruan Avatar
    Ruan

    •

    This doc is out of date. Bunch of things have been updated and doesn’t work any more

  2. hunter melnick Avatar
    hunter melnick

    •

    i am having an issue that the @ViewChild(‘map’) is expecting two arguments, the code runs but because of this error i am unable to run ng build or compile anything. Do you have a fix with the arguments that I can plug in there? I tried to declare some options and plug them in there but nothing was working. If you could please shoot me an email I would really appreciate it. Thankyou

    1. Jolly.exe Avatar
      Jolly.exe

      •

      try replacing

      @ViewChild(‘map’)

      with

      @ViewChild(‘map’, {static: false})

      1. Vikash Avatar
        Vikash

        •

        I tried all possible way but I am unable to see the Map on page for iOS device it works on browser but not in iOS

    2. Ash Avatar
      Ash

      •

      @ViewChild(‘mapElement’, { static: true }) mapElement: ElementRef;

    3. Jojihe Avatar
      Jojihe

      •

      I solucioned with
      @ViewChildren(‘map’)

  3. Husna Avatar
    Husna

    •

    Hello, I managed to input all the codes in and no errors were found. I got my API key. I input it just the way you did but somehow I could not run it. It says, “This page didn’t load Google Maps correctly. See the JavaScript console for technical details.” Please help, thank you!

  4. Washington Avatar
    Washington

    •

    Error: Unexpected value ‘Geolocation’ imported by the module ‘AppModule’. Please add a @NgModule annotation.

    i get this error. and shows a blank screen

  5. Muhammad Syafie Avatar
    Muhammad Syafie

    •

    Do you know how can i get qibla finder from google into my mobile app?
    im using ionic 4

    1. Jolly.exe Avatar
      Jolly.exe

      •

      In Qibla Finder app, Google is just pointing the location of Kaaba (Lat 21.4224779 Long 39.8251832) and your current location. So you can easily create you own app using Google maps in Ionic 4 application. Try these Google Map tutorials with Javascript and Native plugin. Let me know if you want me to create a tutorial on Qibla Finder app in Ionic 4 🙂

      1. Muhammad Syafie Avatar
        Muhammad Syafie

        •

        i would love to hve ur tutorial on Qibla finder app 🙂

  6. Ana Karol Avatar
    Ana Karol

    •

    Olá!!! Parabéns pela iniciativa!! Gostaria de saber qual a diferença de usar o Reverse Geocoder nativo e o provido pela API do Google Maps, vc pode me ajudar? No sentido de vantagens e desvantagens… Qual vc considera melhor?

  7. Luisandro Nachtigal Bandeira Avatar

    This not work on device.

    1. Jolly.exe Avatar
      Jolly.exe

      •

      Hi Luisandro, please explain the issue you are facing, please check if credentials are correct for Google API Key

Leave a Reply

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