A Complete Guide to integrate Google Maps with Ionic 4

ionic-google-maps-integration-example

In last lesson, we have learn how to access geolocation in ionic app using cordova-plugin-geolocation, but that's only lat, lng of the user position. In case if you want to display the current position of the user into google map, what you do?

We have 2 methods for integrating Google Map

  1. Using Google Map Javascript API
  2. Using Google Map Cordova Plugin

To integrate google map using javascript, we need to have the API Key & you need to enable billing on you Google console. Please check https://codesundar.com/create-api-key-in-google-console/ for creating API key

Let's start

Let's create new project or you can use your old project

ionic start map blank
cd map
ionic serve

Using Google Map Javascript API

To display Google map in your ionic app, we need to add following javascript in your src/index.html before closing </head>

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=API_KEY"></script>

Then, open your home page & add div for displaying map with required height & width

File: src/app/home/home.page.html

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

    </div>
</ion-content>

Since, we already know, how to access the geolocation in previous lesson, we can directly display the map after fetching the user's location.

  loadMap() {
    let latLng = new google.maps.LatLng(this.lat, this.lng);
    this.map = new google.maps.Map(document.getElementById('map'), {
      zoom: 15,
      center: latLng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapTypeControl: false,
      zoomControl: false,
      streetViewControl: false,
      fullscreenControl: false,
    });
    new google.maps.Marker({
      map: this.map,
      animation: google.maps.Animation.DROP,
      position: latLng
    });
  }

Explanation:

  • we're calling loadMap() after fetching the user's location.& assigned the data into this.lat, this.lng variables
  • we're getting the div using id (#map) & display the map based on the options, where center of the map is your current location
  • We have also used google map Marker for pin your current location

ionic-google-maps-integration-example

Download Ionic Google Map using Javascript example

Display Map using cordova-plugin-googlemaps

If you want to add the map using cordova plugin, first we need to add the plugin using the required api key.

Add plugin

ionic cordova plugin add cordova-plugin-googlemaps --variable API_KEY_FOR_ANDROID="YOUR_ANDROID_API_KEY_IS_HERE" --variable API_KEY_FOR_IOS="YOUR_IOS_API_KEY_IS_HERE"

npm install --save @ionic-native/google-maps

Now, you need to add the following lines in config.xml

<preference name="GOOGLE_MAPS_ANDROID_API_KEY" value="YOUR_API_KEY" />
<preference name="GOOGLE_MAPS_IOS_API_KEY" value="YOUR_API_KEY" />

After Adding the plugin & configuration, we need to declare it inside app/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 { GoogleMaps } from '@ionic-native/google-maps/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot({ mode: 'md' }), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    Geolocation,
    GoogleMaps,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Explanation:

  • Here, we have declared the GoogleMaps plugin

File app/home/home.page.html

<ion-header>
    <ion-toolbar color="primary">
        <ion-title>
            codesundar.com
        </ion-title>
        <ion-buttons slot="end">
            <ion-button (click)="loadMap()">Map</ion-button>
        </ion-buttons>
    </ion-toolbar>
</ion-header>

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

    </div>
</ion-content>

Explanation:

  • We have created a div tag for using id="map" with height & width of 100%
  • We also created a button in header, when user click the button, we call loadMap()

Explanation: We added map with full width

File app/home/home.page.ts

  loadMap() {
    console.log("loadMap");
    this.map = GoogleMaps.create('map', {})
    this.map.on(GoogleMapsEvent.MAP_READY).subscribe((m) => {
      console.log(m)
      // Access user's current position
      this.map.getMyLocation().then((location) => {
        let latLng = new LatLng(location.latLng.lat, location.latLng.lng);

        // create a marker on your current location
        this.map.addMarker({
          position: latLng,
          title: "My Location"
        }).then(() => {

          // move to camera position to current location
          this.map.moveCamera({ target: latLng, zoom: 12 })
        })
      })
    })
  }

Explanation:

  • When user click the button, we're calling loadMap()
  • Inside loadMap() , we're creating googleMap based on id.
  • we use GoogleMapsEvent.MAP_READY to detect map is ready on not.once map is ready, we're getting the current position & we have added the marker.

Download Ionic Native Google Map Example

Output

ionic-cordova-google-maps-integration-example

Reference