Ionic [2|3] | Integrating Google Maps

Written by on October 20, 2017

Ionic [2|3] | Integrating Google Maps

This guide will walk you through writing a simple Ionic framework application that utilizes Google Maps JavaScript API. It is also important to mention that we will cover what is now known as Angular (Angular 2|4), not what was used to be known as Angular 1. If you came here for the original Ionic 1 example them please find it here.

You will also be able to learn how to use 3rd party JavaScript libraries with the Ionic framework. On the other hand, if you came here looking for a Native Ionic solution then, by all means, find it here.

This guide will not require a real smartphone device as Google Maps Javascript API works in all modern browsers, but I encourage you to try it anyway.

Note: If this tutorial was helpful, you need further clarification, something is not working or you have a request for another Ionic post? Furthermore, leave me a comment below if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com. Thanks and have a nice day!

Preparations

You should have everything set up and working before we can begin.

Make sure you have these:

  • Android Environment (or iOS if you’re working on a MacOS)
  • nodeJS
  • Ionic 2
  • Cordova

Find more information here: IONIC 2 | INSTALLATION GUIDE if you don’t have a previous Ionic 2 installation or if you have never read my previous articles on this topic.

1. Update Ionic & Cordova

As we are working with the NodeJS make sure you have the latest version, without it, you’ll not be able to install/update Cordova and Ionic appropriately. Worst case scenario, have as recent version as possible.

If you already have a working Ionic environment make sure it’s up to date, older versions may not work with this guide. Though sometimes, the latest versions may also mess things up, it’s up to you:

npm install -g ionic cordova

or to do a simple update:

npm update -g ionic cordova

2. Create A New Project

ionic start IonicGoogleMaps blank
cd IonicGoogleMaps 

You can find a working example at the end of this article if you’re an impatient type. Just follow the provided README.md instructions.

Warning: As some of you don't have a prior Ionic CLI experience, from this point and on, every time I tell you to execute something, do that inside an example project folder.

3. Add A Required Platform

Add Android platform:

ionic cordova platform add android

MacOS users can also add iOS platform:

ionic cordova platform add ios

Example

First take a look at this embedded example:

Ionic 2 Google Maps Example

Source Walkthrough

Before we can do anything, we need to include Google Maps Javascript API SDK library. Go to your new project, open src folder and edit index.html. Add this line just above cordova.js line:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=<API KEY GOES HERE>" type="text/javascript"></script>

It should look like this:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=<API KEY>" type="text/javascript"></script>
<!-- cordova.js required for cordova apps -->
<script src="cordova.js"></script>

If you carefully look, you’ll notice that provided Google Maps link is not correct. That’s because it’s missing an API key, acquire it here. Just follow the instructions as it’s free of charge.

If your Google Maps link looks like this:

<script src="http://maps.google.com/maps/api/js?sensor=true"></script>

Remove the sensor parameter, it’s no longer important, Google Maps library will throw an error if you leave it as it is. The error looks like this:

Google Maps API warning: SensorNotRequired: https://developers.google.com/maps/documentation/javascript/error-messages

We are now ready to activate a map. For that, we need to wait for the right moment. Before we would do it during Platform device ready state but it is no longer available. Instead, we will use ionViewDidLoad function. This name tells you everything, it will trigger when IonView component is loaded.

ionViewDidLoad(){
	this.initializeMap();
}

Function content looks like this:

initializeMap() {

	let locationOptions = {timeout: 20000, enableHighAccuracy: true};

	navigator.geolocation.getCurrentPosition(

		(position) => {

			let options = {
			  center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
			  zoom: 16,
			  mapTypeId: google.maps.MapTypeId.ROADMAP
			}

			this.map = new google.maps.Map(document.getElementById("map_canvas"), options);
		},

		(error) => {
			console.log(error);
		}, locationOptions
	);
}

As you can see from this example, initializeMap function will trigger only when IonView component is loaded.

Google maps require a div container for a map to be drawn on, we will call it map_canvas:

<ion-content>
	<div id="map_canvas"></div>
</ion-content>

Last but not least, a div tag is a block element and it requires predefined width and height:

page-home {
	#map_canvas {
		width: 100%;
		height: 100%;
	}
}

That’s everything you need to do, it’s as simple as that.

If you deploy this code inside a web browser (from your project folder of course):

ionic serve

You’ll see something like this:

Ionic 2 Google Maps Example

I will not try to explain to you how Google Maps Javascript API works, that’s something you can do on your own.

But there’s one thing I forgot to mention. As we are mixing TypeScript and vanilla Javascript we will get an error “Cannot find name google” and it’s a reference to this line:

center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),

Typescript doesn’t know how to interpret object google. to fix this we need to add this line:

declare var google;

This is a way of telling Typescript “Quit complaining, this variable exists somewhere in JavaScript”.

Source Code

In case GitHub repo is not available and you can only use code provided below, this is what project folder looks like (image was taken from Sublime text editor):

Ionic 2 Google Maps Folder Structure

index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="UTF-8">
  <title>Ionic App</title>
  <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/x-icon" href="assets/icon/favicon.ico">
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4e8ef7">
  
  <!-- 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 async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBN__TGV0kdA7nwr1Nimjqi8XyqIPmF7zA" type="text/javascript"></script>
  <!-- cordova.js required for cordova apps -->
  <script src="cordova.js"></script>

  <!-- un-comment this code to enable service worker
  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.error('Error', err));
    }
  </script>-->

  <link href="build/main.css" rel="stylesheet">

</head>
<body>

  <!-- Ionic's root component and where the app will load -->
  <ion-app></ion-app>

  <!-- The polyfills js is generated during the build process -->
  <script src="build/polyfills.js"></script>

  <!-- The vendor js is generated during the build process
       It contains all of the dependencies in node_modules -->
  <script src="build/vendor.js"></script>

  <!-- The main bundle js is generated during the build process -->
  <script src="build/main.js"></script>

</body>
</html>
home.ts
import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';

declare var google;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

	map: any;

	constructor(private platform: Platform) {

	}

	ionViewDidLoad(){
		this.initializeMap();
	}

	initializeMap() {

		let locationOptions = {timeout: 20000, enableHighAccuracy: true};

		navigator.geolocation.getCurrentPosition(

			(position) => {

				let options = {
				  center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
				  zoom: 16,
				  mapTypeId: google.maps.MapTypeId.ROADMAP
				}

				this.map = new google.maps.Map(document.getElementById("map_canvas"), options);
			},

			(error) => {
				console.log(error);
			}, locationOptions
		);
	} 	
}
home.html
<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Google Maps Example
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
	<div id="map_canvas"></div>
</ion-content>
home.scss
page-home {
	#map_canvas {
		width: 100%;
		height: 100%;
	}
}

Deployment

Next step, build our application:

ionic build android

Be careful here, this step may break if you’re behind a firewall. The first execution will take a long time, so be patient.

Finally:

ionic run android -l -c -s

or if you want to test it in your browser:

ionic serve -l -c -s

Download The Code

Working GitHub repo link can be found below:

GitHub
Categories

20 thoughts on “Ionic [2|3] | Integrating Google Maps”

  1. Above code new google.maps —google is not support in visual studio code ,can u please tell the solution.

      • If you don’t want to install the typescript definition file, you could also just declare the google variable on top of your script as follows:
        declare var google: any
        This should stop typescript from giving an error and everything should work as expected.

  2. Did exactly as written, displays google maps container with the Google logo but its plain grey and no map is shown.

  3. The instructions are a little hard to understand for a newbie:

    “Open app directory and remove all content from a directory called pages but don’t delete it. Somewhere below you’ll find a link to GitHub repo holding a working example (or you can copy past provided code). Download zipped project repo folder, copy app and www directory and past it into a newly created folder.”

    But after creating the project with “ionic start…” as instructed there is no app directory and no app/pages directory. So which directories are meant here?
    Also copying IN the app and www directories into the new root directory “Ionic2GoogleMaps” (I assume this is the “newly created folder”) – is that right? We are told to e.g. edit www/index.html but this is overwritten later on by “ionic serve”.

    • That was probably a byproduct of my site beed hacked. Now everything should be back to normal. Though I will go through all my articles just to make sure that everything is ok.

Leave a Reply