Google Map integration in Ionic 2 using JavaScript API

The JavaScript API which i am going to use for google maps integration in Ionic 2 works well on all mobiles. Follow the below steps to integrate google map in Ionic 2.

Creating an Ionic 2 Application:

ionic start maps blank --v2

Learm More at http://www.codeexpertz.com/blog/mobile/creating-android-application-using-ionic-framework

 

Adding the plugins:

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

Run the above commands from the root of the Ionic 2 project. This will install GeoLocation Cordova Plugin and the Ionic Native Package for GeoLocation in your project

13.PNG

Get the API KEY for Google Maps Integration:

SignUp for an Account and Create a Project at https://console.developers.google.com/apis/dashboard

Once the project has been created goto https://developers.google.com/maps/documentation/javascript/get-api-key to generate the key. Follow the screens below.

Step 1 - Create Project from DashBoard:

7.png

Step 2:

8.png

Step 3:

9.png

Getting API KEY:

6.png

 

10.png

 

11.png

Once you get the key Add this Script above the cordova.js in your src/index.html file with the API KEY

http://maps.google.com/maps/api/js?key=PASTE-API-KEY-HERE

5.PNG

Add providers app.module.ts:

4.PNG

home.html File:

This will have a "div" tag to load the MAP. A "+Add Marker" placed at the header to incert the MAP MARKER Icon at the center of the Google Map.

3.PNG

home.ts File:

Import the ViewChild, ElementRef, and Geolocation. Declare a "google" before the decorator, in order prevent any warnings from TypeScript about the google object.

The function "loadMap()" is called inside "ionViewDidLoad()" function. The difference between the constructor and the ionViewDidLoad is if you want to interact with the DOM in the constructor, you will notice that the DOM is not ready. and you won't be able to get the element. The correct approach to do it will be inside the ionViewDidLoad because at that point the view was already loaded and the DOM is now available. This is just like a $(document).load() function at jQuery.

1.PNG

2.PNG

OUTPUT:

map.PNG

// app.module.ts File
---------------------------
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
 
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
 
// app.module.ts File
 
import { Geolocation } from '@ionic-native/geolocation'; // Newly Added
 
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
 
@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ListPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    ListPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    Geolocation, // Newly Added
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}
 
 
// home.ts File
------------------
 
import { Component, ViewChild, ElementRef } from '@angular/core'; // Added  ViewChild, ElementRef
import { NavController } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation'; // Newly Added
 
declare var google; // Added
 
@Component({
  selector: 'home-page',
  templateUrl: 'home.html'
})
export class HomePage {
 
  @ViewChild('map') mapElement: ElementRef; // Added
  map: any; // Added
 
  constructor(public navCtrl: NavController, public geolocation: Geolocation) { // Added public geolocation: Geolocation
 
  }
 
  ionViewDidLoad() { // Added this function to loadMap
    this.loadMap();
  }
//home.ts File
  loadMap() {
    this.geolocation.getCurrentPosition().then((position) => {
      let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      let mapOptions = {
        center: latLng,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
    }, (err) => {
      console.log(err);
    });
  }
 
  addMarker() { // To Add Marker
    let marker = new google.maps.Marker({
      map: this.map,
      animation: google.maps.Animation.DROP,
      position: this.map.getCenter()
    });
    let content = "<h3>My New Location!</h3><h5>by Anish youtube - Please subscribe</h5>";
    this.addInfoWindow(marker, content);
  }
 
  addInfoWindow(marker, content) {
    let infoWindow = new google.maps.InfoWindow({
      content: content
    });
    google.maps.event.addListener(marker, 'click', () => {
      infoWindow.open(this.map, marker);
    });
  }
 
}
 
 
// home.scss
----------------
.md {
 
    home-page {
 
      .scroll {
        height: 100%
      }
 
      #map {
        width: 100%;
        height: 100%;
      }
 
    }
 
}
// home.scss
----------------
.md {
 
    home-page {
 
      .scroll {
        height: 100%
      }
 
      #map {
        width: 100%;
        height: 100%;
      }
 
    }
 
}
 <!-- src/index.html-->
 
  <script src="http://maps.google.com/maps/api/js?key=AIzaSyAdfwkFsdfBjMnIBIt_Wm78KJHPzWbA"></script> <!-- Include MAPS API with your API KEY-->
 
<!-- home.html File -->
 
<ion-header>
  <ion-navbar>
    <ion-title>
      Google Map Integration.
    </ion-title>
    <ion-buttons end>
      <!-- Button to Add Location Marker -->
      <button ion-button (click)="addMarker()"><ion-icon name="add"></ion-icon>Add Marker</button> 
    </ion-buttons>  
  </ion-navbar>
</ion-header>
 
<ion-content>
  <div #map id="map"></div>  <!-- To Load MAP -->
</ion-content>
Category: