How to add a google map in Ionic 4

Share the post

Hello All, In the last topic of Ionic 4, We had discussed How to use SAAS mixin in Ionic 4 applications. Now, In this topic, We will discuss How to add a google map in the Ionic 4 application. What are the basic steps required to add Google Maps in the Ionic application? If you want to see How to implement Google maps in the Ionic 3 application then I have already made a tutorial for this here.

Steps required to add Google Maps In the Ionic application

Step 1: Create a new project using Ionic CLI.

Step 2: Create a new page using CLI

ionic g page display-maps

Write the above command to generate a new page in the Ionic 4 application.

Step 3: Install the dependency of google maps

npm install @types/googlemaps --save-dev

We have to add the above dependency using

Step 4: Add script file in index.html

  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

After adding the dependencies add the google maps API script in index.html. This is the most important step otherwise you will face errors.

Step 5:Write the HTML file to display Google Maps

<ion-header>
  <ion-toolbar>
    <ion-title>Display maps in Ionic 4 application</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-card>
    <ion-card-header>Google Maps</ion-card-header>
    <div id="myMapElement" class="viewMap"></div>
    <ion-card-content>

    </ion-card-content>
  </ion-card>

</ion-content>

Here, We include the div inside Ion-card to get a better display of the map.

Step 6: Add required CSS

In the above HTML, We have added only one CSS for viewMap. The code for viewMap is as follows

.viewMap{
    height: 350px;
}

Step 7: Write typescript code as follows

  • Import the google maps module as follows
import { } from 'googlemaps';
  • Now, write below code in your display-maps.page.ts file
import { Component, OnInit, ViewChild } from '@angular/core';
import { } from 'googlemaps';

@Component({
  selector: 'app-display-maps',
  templateUrl: './display-maps.page.html',
  styleUrls: ['./display-maps.page.scss'],
})
export class DisplayMapsPage implements OnInit {

  myMap: any;

  constructor() { }

  ngOnInit() {
    this.displayMaps();
  }

  displayMaps() {
    console.log("displayMaps");
    this.myMap = new google.maps.Map(document.getElementById('myMapElement'),{
      zoom: 10,
      center: { lat: 19.035145, lng: 72.715102 }
    });


  }

}

Step 8 : Create new file under src folder

Now, we have to create a new file under the src folder. Rename this file as index.d.ts

Write below code in this file

declare module 'googlemaps';

Step 9: Output

Now, We can able to see google maps in our Ionic 4 application

output_img_display_maps
Output

This is how we can able to implement Google Maps in the Ionic 4 application.

1 thought on “How to add a google map in Ionic 4”

Leave a Comment