Last update on Saturday, July 1st 2017

Introduction to Ionic Google Analytics

Understanding how users interact with your applications is crucial, which video is generally watched, which character is generally played, which feature is not used, many insights that can drive away the users or increase their engagement.
Google Analytics is dominating the subject, they started first and injected a **** lot of money in their technology.
In this tutorial we will have a look at how we can use it in a HTML5 mobile application with Ionic.
The application will be very simple, we will track when a user arrives on the Home Page and when he answers a question.

Setup

As usual we start by creating our application and installing Cordova and Ionic plugins:

ionic start ionic-analytics blank
ionic cordova plugin add cordova-plugin-google-analytics
npm install --save @ionic-native/google-analytics

Good news, a mobile device is not required to use Google Analytics.

We can use the browser platform. This platform is an improved version of your current browser, some Cordova plugins work with it which is awesome for debugging!

We first need to install it:

ionic cordova platform add browser

Normally the browser can be run with livereload like this:

ionic cordova run browser --livereload

However, a recent change broke it. Thanks to the Ionic community, a workaround was found, you can use this for now:

./node_modules/.bin/ionic-app-scripts serve --sourceMap source-map --iscordovaserve --wwwDir platforms/browser/www/ --buildDir platforms/browser/www/build

A Google Account account is required to use Analytics.
The signup is there.

Ionic Google Analytics signup

A new property is required, basically one for each application or website we need to track:

Ionic Google Analytics create property

Nothing complicated here:

Ionic Google Analytics setup property

A new Account Name because it's a brand new Google Analytics account and the name of the application.

We finally access this:

Ionic Google Analytics get tracking id

Our Tracking ID!

We can now start coding.

Page View

Our first objective is to track when a user visits the Home Page, but first we add GoogleAnalytics to the list of providers:

import { GoogleAnalytics } from '@ionic-native/google-analytics';
.
.
.

@NgModule({
  .
  .
  .
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    GoogleAnalytics
  ]
})

And setup the home.ts file:

import { GoogleAnalytics } from '@ionic-native/google-analytics';

export class HomePage {

  constructor(public ga: GoogleAnalytics) {
    this.ga.startTrackerWithId('UA-101858534-1')
      .then(() => {
        console.log('Google analytics is ready now');
        this.ga.trackView('home');
      })
      .catch(e => console.log('Error starting GoogleAnalytics', e));
  }
}

The GoogleAnalytics Service will be stocked in a property, the tradition is to call it ga.
The startTrackerWithId method will init our Service with our Tracker ID, once this is done the trackView method will notify that the Home Page has a new View. Every time this event will be triggered, it will increment the number of PageViews for the Home Page.

Launching our app, we have our first View detected!

Ionic Google Analytics first view

This is only available in the REAL-TIME menu and the sub-menu Overview, you will know the reason later.

We can now move forward, our next goal: tracking a custom event!

Event Tracking

Here is the home.html file that will be used:

<ion-content padding>

  <ion-label>
    How many hours do you spend online?
  </ion-label>

  <input type="text" [(ngModel)]="number">

  <br>

  <button ion-button [hidden]="hasAnswered" (click)="answer(number)">
    Answer
  </button>

  <div [hidden]="!hasAnswered">
    Thanks for your answer!
  </div>

</ion-content>

Just a simple question for the user, the number property will stock the answer and the hasAnswered property will show a thank you message once the question is answered.

The answer method will be used to trigger Google Analytics event, which is as follow:

export class HomePage {
  hasAnswered = false;

  answer(number) {
    this.ga.trackEvent("form", "vote", "Hours online", number).then(() => {
      this.hasAnswered = true;
    });
  }
}

(Don't forget to initialize the hasAnswered property to false).
The trackEvent method signature is as follow:

trackEvent(category, action, label, value, newSession)

We won't use the newSession parameter. All the other parameters are strings except the value, which is a number.

All of those information are custom, nothing set in stone.
The category is named "form" because it's form related, you can create your own like Videos, Downloads, etc.
The action is "vote", you can call it play, pause, download, etc.
The label is "Hours online" to track the corresponding question.
Finally the value is the answered number.

Moving to the Events sub-menu, you have the event triggered when the question is answered!

Ionic Google Analytics first event

Ok I have to tell you one thing that can make you sad ...
Until now we have used the REAL-TIME menu.
If we move to BEHAVIOR -> Events -> Overview:

Ionic Google Analytics overview event

There is nothing...
This is where all the data are stocked.

You’d say “that’s ok we have the Real-Time area where we have the data”, well … not really, the value that you pass when answering the question in the application is only available in the BEHAVIOR view, not the Real-Time one and this view generally takes one or two days to refresh.

Furthermore Google Analytics only considers that you will need a number for tracking minutes played, number of videos watched, number of downloads, … and that’s not always true.

A workaround would be to simply use the label field to do the work:

this.ga.trackEvent("form", "vote", number, number);

We finally have the values and the count:

Conclusion

We have seen how to track a page View and a Custom Event. An Event is composed of a category, an action, a label and a value.
It requires a lot of processing time before being registered in Google Analytics, this time is required so Analytics can make some statistics with the values and display it on the Overview report page.
Gathering data on users is super important to improve a mobile application and see what they like and what they don’t like.
With great power comes great responsibility so don’t be evil 😉. If you handle Google Analytics in another way don’t hesitate to comment.

Implementing Native Google Maps in an Ionic Application

Making Phone Calls to Contacts with Ionic in one go

Mastering File Navigation with Ionic Native File

Stay up to date


Join over 4000 other developers who already receive my tutorials and their source code out of the oven + other free stuff!