You are on page 1of 25

Tutorial 05: Introduction to Ionic Framework

Overview:
Ionic is open source HTML5 Mobile App Development Framework
targeted at building hybrid mobile apps. It provides tools and services for
building Mobile UI with native look and feel. Ionic framework needs native
wrapper to be able to run on mobile devices.
Since Ionic is built on top of AngularJS and Apache Cordova, you will need
to have basic knowledge about these technologies. You also need to be
familiar with HTML, CSS and JavaScript, if you want to understand all the
information provided.
Ionic Framework Features
Following are the most important features of Ionic:
 AngularJS − Ionic is using AngularJS MVC architecture for building
rich single page applications optimized for mobile devices.
 CSS components − With the native look and feel, these components
offer almost all elements that a mobile application needs. The
components’ default styling can be easily overridden to accommodate
your own designs.
 JavaScript components − These components are extending CSS
components with JavaScript functionalities to cover all mobile elements
that cannot be done only with HTML and CSS.
 Cordova Plugins − Apache Cordova plugins offer API needed for using
native device functions with JavaScript code.
 Ionic CLI − This is NodeJS utility powered with commands for starting,
building, running and emulating Ionic applications.
 Ionic View − Very useful platform for uploading, sharing and testing
your application on native devices.
 Licence − Ionic is released under MIT license.
Install Ionic:
First, install Node.js. Then, install the latest Ionic command-line tools in your
terminal. You can download Node.js from Node JS website
(https://nodejs.org/en/ ). Open download page.
Page 1 of 25 Mohammed Mahmoud
Select the appropriate version for your Operating system and platform. Install
Node.js after download process finished.
To install ionic open the command prompt and type the following command.
You have to be connected.
npm install -g cordova ionic

You can create ionic application using one of Ionic application template blank,
tabs or sidemenu.

ionic start myApp blank

Page 2 of 25 Mohammed Mahmoud


ionic start myApp tabs

ionic start myApp sidemenu

Create Blank App:


If you want to start from the scratch, you can install the Ionic blank template.
We will use the following command to create ionic blank app ionic start
futureApp blank.
C:\Users\Username\Desktop> ionic start futureApp blank

The Ionic Start command will create a folder named futureApp and setup
the Ionic files and folders.

Page 3 of 25 Mohammed Mahmoud


C:\Users\Username\Desktop> cd futureApp

Test your App in Browser:


Since we are working with the JavaScript, you can serve your app on any web
browser. This will speed up your building process, but you should always test
your app on native emulators and devices. Type the following code to serve
your app on the web browser.
C:\Users\Username\Desktop\futureApp> ionic serve

The above command will open your app in the web browser. Google Chrome
provides the device mode functionality for mobile development testing.

Add Google Map to your App:


Google Maps is a free web mapping service by Google that provides various
types of geographical information. Google Maps has a JavaScript API to
customize the maps and display them on your webpage.

Page 4 of 25 Mohammed Mahmoud


Google Maps provides an API using which you can customize the maps and
the information displayed on them. This tutorial explains how to load a simple
Google Map on your web page using HTML and JavaScript. We will use
Microsoft Visual Studio Code as code editor.

Let us to download Microsoft Visual Studio Code, Microsoft Visual Studio


Code is a source code editor developed by Microsoft for Windows, Linux and
macOS. It includes support for debugging, embedded Git control, syntax
highlighting, intelligent code completion, snippets, and code refactoring. It is
also customizable, so users can change the editor's theme, keyboard shortcuts,
and preferences. It is free and open-source, although the official download is
under a proprietary license. To download Microsoft Visual Studio Code go to
the Microsoft Visual Studio Code Website (https://code.visualstudio.com/ ).

Click on Download button to open download page.

Page 5 of 25 Mohammed Mahmoud


Download the appropriate version for your Operating System. When
download finish double click installer software to install Microsoft Visual
Studio Code.

Page 6 of 25 Mohammed Mahmoud


The main interface of Microsoft Visual Studio Code. Now we will open
futureApp ionic project in Microsoft Visual Studio Code. Click Open Folder
under start section or from main menu of Microsoft Visual Studio Code click
File and then click Open Folder. Navigate to your project folder.

Select your ionic project folder and then click on Select Folder button.

Page 7 of 25 Mohammed Mahmoud


Now you can see your project files in the Explorer panel. Open
src/pages/home.html page.

<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>
The world is your oyster.
<p>
If you get lost, the <a href="http://ionicframework.com/docs/v2">docs</a>
will be your guide.
</p>
</ion-content>

Change the content of <ion-title> tag to The Future University and remove
the content of <ion-content> tag and add a new <div> tag with “mapDiv” id
and set the height property to 100%. Your home page should look like the
following code.

Page 8 of 25 Mohammed Mahmoud


<ion-header>
<ion-navbar>
<ion-title>
The Future University
</ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>
<div id="mapDiv" style="height:100%;"></div>
</ion-content>

When you open your application in the browser it should look like the
following screenshot.

Page 9 of 25 Mohammed Mahmoud


Now open the src/index.html page. To add google map API and javascript
code to show google map inside your application.

<!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">

<!-- cordova.js required for cordova apps (remove if not needed) -->
<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>

Page 10 of 25 Mohammed Mahmoud


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

</body>
</html>

Inside the head section add the following code to load google map api in your
application. To include google map API in your page you need google map
key. Go to google developer website and generate a key.

<script src="https://maps.googleapis.com/maps/api/js?key=setYourKeyHere"></script>

Inside the body section, add the following JavaScript code to load google map
in your page.

<script>
var map = new google.maps.Map(document.getElementById('mapDiv'), {
center: new google.maps.LatLng(15.4325, 32.4321), zoom:6
});
</script>

Save your updates and go to the browser, your application should look like
the following.

Page 11 of 25 Mohammed Mahmoud


Add a New Page to Your Application:

let’s walk through the process of creating and navigating to pages in our app.
Taking a look at src/app/app.html, we see this line of code.

<ion-nav [root]="rootPage"></ion-nav>

Page 12 of 25 Mohammed Mahmoud


Pay attention to the [root] property binding. This sets what is essentially the
first, or “root” page for the ion-nav component. When ion-nav loads, the
component referenced by the variable rootPage will be the root page.

In src/app/app.component.ts, the MyApp component specifies HomePage as


the root page by assigning it to the rootPage variable.

import { Component } from '@angular/core';


import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HomePage } from '../pages/home/home';


@Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any = HomePage;

constructor(platform: Platform, statusBar: StatusBar, splashScreen:


SplashScreen) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
});
}
}

We see that rootPage is set to HomePage, so HomePage will be the first page
loaded in the nav controller. Let’s take a look at it.

<ion-header>
<ion-navbar>
<ion-title>
The Future University
</ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>

Page 13 of 25 Mohammed Mahmoud


<div id="mapDiv" style="height:100%;"></div>
</ion-content>

let’s check out the home that we are importing. Inside the src/pages/home/
folder, go and open up home.ts.

import { Component } from '@angular/core';


import { NavController } from 'ionic-angular';

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

constructor(public navCtrl: NavController) {

You may have noticed that each page has its own folder that is named after
the page. Inside each folder, we also see a .html and a .scss file with the same
name. For example, inside of home/ we will find home.ts, home.html,
and home.scss. Although using this pattern is not required, it can be helpful to
keep things organized.

Below, we see the home class. This creates a Page - an Angular component
with all Ionic directives already provided, to be loaded using Ionics’s
navigation system. Notice that because Pages are meant to be loaded
dynamically, they don’t need to have a selector. However, the selector is
useful in order to override the default styles on a specific page
(see home.scss): All pages have both a class, and an associated template that’s
being compiled as well.

Page 14 of 25 Mohammed Mahmoud


Creating a new Page:

To create an additional page, we do not need to do much. Just open the


command window and type the following command:

C:\Users\hp\Desktop\ionicProjects\futureApp>ionic g page gps

A gps folder will created automatically inside pages directory of your project.

Page 15 of 25 Mohammed Mahmoud


To add the new page to your application open app.modules.ts
src/app/app.modules.ts. Under import {HomePage} add the following code
to add your page to the app.

import { HomePage } from '../pages/home/home';


import { GpsPage } from '../pages/gps/gps';

And inside NgModule declaration add your page name.

Page 16 of 25 Mohammed Mahmoud


@NgModule({
declarations: [
MyApp,
HomePage,
GpsPage
],

And inside bootstrap entryComponents add your page name.

bootstrap: [IonicApp],

entryComponents: [

MyApp,

HomePage,

GpsPage

],

Now inside home page let us to add a new button. We will use this button to
open gps page.

<ion-content padding>
<button ion-button full>Open GPS</button>
<div id="mapDiv" style="height:100%;"></div>
</ion-content>

now we will add click event for the button. In button tag add click event.

<button ion-button full (click)="openGPS()">Open GPS</button>

Open src/pages/home.ts and create openGPS() method. And you have to


import GpsPage.

import { Component } from '@angular/core';


import { NavController } from 'ionic-angular';
import { GpsPage } from '../gps/gps';

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

Page 17 of 25 Mohammed Mahmoud


constructor(public navCtrl: NavController) {

}
openGPS(){
this.navCtrl .push(GpsPage);
}

Now open your application in browser.

Page 18 of 25 Mohammed Mahmoud


When you click on the open GPS button.

Page 19 of 25 Mohammed Mahmoud


Open src/pages/gps/gps.html and change the content of <ion-title> and add
to three textbox field inside the <ion-contenet> tag.

<ion-header>

<ion-navbar>

Page 20 of 25 Mohammed Mahmoud


<ion-title>GPS Coordinates</ion-title>
</ion-navbar>

</ion-header>

<ion-content padding>

<ion-list>

<ion-item>
<ion-label floating>Longitude</ion-label>
<ion-input type="text"></ion-input>
</ion-item>

<ion-item>
<ion-label floating>Latitude</ion-label>
<ion-input type="text"></ion-input>
</ion-item>

<ion-item>
<ion-label floating>Accuracy</ion-label>
<ion-input type="text"></ion-input>
</ion-item>

</ion-list>

<button ion-button full>Get Current Position</button>

</ion-content>

Page 21 of 25 Mohammed Mahmoud


Add Geolocation Plugin:

The Geolocation API is the perfect companion for a maps application – maps
deal with locations, and the Geolocation API allows you to retrieve a user’s
location. If you are running this on a device, make sure to install the
Geolocation plugin by running:

ionic cordova plugin add cordova-plugin-geolocation

Page 22 of 25 Mohammed Mahmoud


You will also need to install the Ionic Native package for this plugin with the
following command:

npm install --save @ionic-native/geolocation

Import Geolocation. Moreover, add Geolocation as a provider in your


src/app/app.module.ts file:

import { Geolocation } from '@ionic-native/geolocation';


.
.
providers: [
StatusBar,
SplashScreen,
Geolocation,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]

Geolocation will also work directly through the browser though, as it is part
of the HTML5 API. Let us to add (click) event for Get Current Position
button in src/pages/gps/gps.html.

<button ion-button full (click)="getCoords()">Get Current Position</button>

Add identifier to the Longitude, Latitude and Accuracy input fields.

<ion-content padding>

<ion-list>

<ion-item>
<ion-label floating>Longitude</ion-label>
<ion-input type="text" #lng></ion-input>
</ion-item>

<ion-item>
<ion-label floating>Latitude</ion-label>
<ion-input type="text" #lat></ion-input>
</ion-item>

<ion-item>

Page 23 of 25 Mohammed Mahmoud


<ion-label floating>Accuracy</ion-label>
<ion-input type="text" #acc></ion-input>
</ion-item>

</ion-list>

<button ion-button full (click)="getCoords()">Get Current Position</button>


</ion-content>

Let us modify our src/pages/gps/gps.ts file to make use of Geolocation now.


First, import Geolocation class.

import { Geolocation } from '@ionic-native/geolocation';

Within the export class GpsPage add the input fields as objects. Moreover,
add geolocation object as a parameters to the constructor method.

export class GpsPage {

@ViewChild('lng') lng;
@ViewChild('lat') lat;
@ViewChild('acc') acc;

constructor(public navCtrl: NavController, public navParams: NavParams,


public geo: Geolocation) {
}

Now create getCoords() handler for Get Current position button.

getCoords(){
this.geo.getCurrentPosition().then((position)=>{
this.lng.value = position.coords.longitude;
this.lat.value = position.coords.latitude;
this.acc.value = position.coords.accuracy;
}).catch((error)=>{
console.log(error);
});
}

Save your application and use the ionic serve command to test your
application in browser. Click on GET CURRENT POSITION button.

Page 24 of 25 Mohammed Mahmoud


Page 25 of 25 Mohammed Mahmoud

You might also like