How To Add Reminder In Ionic 2

Hardik_aug
A calendar is a very useful tool to remind you about time-specific events in your day to day life. It gives you the facility to track your events and as a result, you can use your brain in many other creative things than to keep reminding yourself about some specific events in your life.

Let’s start with integrating the reminder in your application using ionic. Below are the steps for the same.

Steps:

First, add ionic native calendar Cordova plugin in your application.

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

 

Then import plugin in app.module.ts file.

import { Calendar } from ‘@ionic-native/calendar’

Then add createEvent() function for creating an event in the calendar and passing parameter following to ionic docs.

this.calendar.createEvent(title, location, notes, startDate,    endDate).then(
		   (msg) => { alert(msg); },
		   (err) => { alert(err); }
	); 

 

Then create html form for getting user calendar event data.

<form (submit)="getCalender()">
	   <ion-item>
          <ion-label>Title</ion-label>
          <ion-input type="text" [(ngModel)]="title" name="title"></ion-input>
      </ion-item>

      <ion-item>
          <ion-label>Note</ion-label>
          <ion-input type="text" [(ngModel)]="notes" name="notes"></ion-input>
      </ion-item>

      <ion-item>
          	<ion-label>Location</ion-label>
<ion-input type="text" [(ngModel)]="location" name="location"></ion-input>
      </ion-item>

      <ion-item>
          <ion-label>Start Date</ion-label>
<ion-datetime displayFormat="DD MMM YYYY" [(ngModel)]="startDate" name="startDate"></ion-datetime>
      </ion-item>

      <ion-item>
<ion-label>Start Time</ion-label>
<ion-datetime displayFormat="hh:mm:a" [(ngModel)]="startTime" name="startTime"></ion-datetime>
      </ion-item>

      <ion-item>
      <ion-label>End Date</ion-label>
<ion-datetime displayFormat="DD MMM YYYY" [(ngModel)]="endDate" name="endDate"></ion-datetime>
      </ion-item>

      <ion-item>
<ion-label>End Time</ion-label>
<ion-datetime displayFormat="hh:mm:a" [(ngModel)]="endTime" name="endTime"></ion-datetime>
      </ion-item>

      <br><br>
      <button ion-button full>Submit</button>
	</form>

 

Now add two different field for time and date in event form and marge date and time and convert javascript ISO Date() format.

getCalender(){		
var startDateTimeISO = this.buildISODate(this.startDate, this.startTime);
var enddateTimeISO = this.buildISODate(this.endDate, this.endTime);
        	
this.calendar.requestWritePermission();	this.calendar.createEvent(this.title, this.location, this.notes, new Date(startDateTimeISO), new Date(enddateTimeISO)).then(
		        (msg) => { alert('msg '+msg); },
		        (err) => { alert('err '+err); }
);	
 }

buildISODate(date, time){
      var dateArray = date && date.split('-');
      var timeArray = time && time.split(':');
var normalDate = new Date(parseInt(dateArray[0]), parseInt(dateArray[1])-1, parseInt(dateArray[2]), parseInt(timeArray[0]), parseInt(timeArray[1]), 0, 0);
      return normalDate.toISOString();
  }

 

Then adding event notification add ionic local notification plugin.

    ionic cordova plugin add de.appplant.cordova.plugin.local-notification
npm install –save @ionic-native/local-notifications

Then import plugin in app.module.ts file.

    import { LocalNotifications } from ‘@ionic-native/local-notifications’;

Now add notification module in your submission form function.

 this.localNotifications.schedule({
		   	   title: this.title,
			   text: this.notes,
			   at: new Date(startDateTimeISO),
			   led: 'FF0000',
			   sound: null
		});

 

Then add Cordova platform which you prefer.

     ionic cordova platform add ios
ionic cordova platform add android

Now run your ionic application on your device.

      Ionic cordova run android –device

Hope this blog helped you to learn how to add Reminder in Ionic 2 quickly. Need more assistance regarding Hybrid App Development Contact us now!

 

Advertisements

Find Near By Location In Ionic 3 Using Google Map API

Find-nearby-location-in-ionic-3

Google nearby location:-

Maps are always needed for finding the nearby places for our daily routine work. Here is the simple example how we can use the google map API in ionic 3 application for finding the nearby places like: hospital, restaurant, bank, airport, library, gym, etc.

Google Maps API will be used to display the maps. There are lot of things you can do with the maps API like find the nearby places, get the direction between two places etc. We will explore how to apply place recommendations and suggestions using Google Places API.

Steps:

First, install the google map library using this.

npm install @types/googlemaps --save-dev

Now go to node_modules and then @types and inside that Google maps folder and add line

declare module 'googlemaps';

Now we will use the google map js library for getting informed about the places. So include the Google Map js file in the index.html file.

 

<script src="http://maps.google.com/maps/api/js?key=XXXXX=places"></script>

The above script needs the google map API key. Follow these steps:-

  • Go to https://console.developers.google.com
  • Create a new Google project and give an appropriate name to your project
  • Once you created a new project, it will redirect you to the API section and click the google maps Javascript API
  • Click the enable API. Then click the create credentials and click the what credentials do I need?
  • That’s all. It will give you the google map API key

Then install geolocation plugin in order to access the user location.

 

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

Now to import geolocation plugin in app.module.ts file.

 

import { Geolocation } from '@ionic-native/geolocation';      
@NgModule({    
     ...   
     providers: [  Geolocation   ]  
     ... })

 

Then import the Google maps class and geolocation plugin to the home.ts file.

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

import { googlemaps } from 'googlemaps';

 

Now use the google map places API like this.

 let service = new google.maps.places.PlacesService(this.map);

Now add this code to your home.ts file.

import { Component, NgZone, ElementRef, ViewChild } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
import { Geolocation ,GeolocationOptions ,Geoposition ,PositionError } from '@ionic-native/geolocation';
import { googlemaps } from 'googlemaps';

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

export class HomePage {

  @ViewChild('map') mapElement: ElementRef;

  map:any;
  latLng:any;
  markers:any;
  mapOptions:any;  
  isKM:any=500;
  isType:any="";
 
  constructor(private ngZone: NgZone, private geolocation : Geolocation) { }

  ionViewDidLoad() {
    this.loadMap();
  }

  loadMap(){

    this.geolocation.getCurrentPosition().then((position) => {

this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

          console.log('latLng',this.latLng);
     
      this.mapOptions = {
        center: this.latLng,
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }   

this.map = new google.maps.Map(this.mapElement.nativeElement, this.mapOptions);

    }, (err) => {
      alert('err '+err);
    });

  }


 /*--------------------Find Nearby Place------------------------*/ 

  nearbyPlace(){
    this.loadMap();
    this.markers = [];
    let service = new google.maps.places.PlacesService(this.map);
    service.nearbySearch({
              location: this.latLng,
              radius: this.isKM,
              types: [this.isType]
            }, (results, status) => {
                this.callback(results, status);
            });
  }

  callback(results, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        this.createMarker(results[i]);
      }
    }
  }

  createMarker(place){
    var placeLoc = place;
    console.log('placeLoc',placeLoc);
    this.markers = new google.maps.Marker({
        map: this.map,
        position: place.geometry.location
    });

    let infowindow = new google.maps.InfoWindow();

    google.maps.event.addListener(this.markers, 'click', () => {
      this.ngZone.run(() => {
        infowindow.setContent(place.name);
        infowindow.open(this.map, this.markers);
      });
    });
  }

}

 

Now Add this code to your home.html file for selecting places type and places distance find nearby places.

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

<ion-content padding>
<ion-item>
<ion-label>Select Place</ion-label>
  <ion-select [(ngModel)]="isType" (ionChange)="nearbyPlace()">
  <ion-option value="">Select</ion-option>
      <ion-option value="hospital">Hospital</ion-option>
      <ion-option value="restaurant">Restaurant</ion-option>
      <ion-option value="bank">Bank</ion-option>
      <ion-option value="airport">Airport</ion-option>
      <ion-option value="library">Library</ion-option>
      <ion-option value="gym">Gym</ion-option>
    <ion-option value="atm">Atm</ion-option>
    <ion-option value="shopping_mall">Shopping Mall</ion-option>
    <ion-option value="police">Police Station</ion-option>
    <ion-option value="zoo">Zoo</ion-option>
  </ion-select>
</ion-item>

<ion-item>
<ion-label>Select Distance</ion-label>
  <ion-select [(ngModel)]="isKM" (ionChange)="nearbyPlace()">
  <ion-option value="500">Select</ion-option>
      <ion-option value="2000">2 KM</ion-option>
      <ion-option value="4000">4 KM</ion-option>
      <ion-option value="6000">6 KM</ion-option>
      <ion-option value="8000">8 KM</ion-option>
  </ion-select>
</ion-item>

<div #map id="map"></div>
    
</ion-content>

 

Hope this helps you well, feel free to add your comments/feedbacks. Need more assistance regarding Ionic App Development Get in touch today!

Multi-Language Functionality In Ionic_v2

Multilingual with Ionic

The Multi-language functionality gives you a facility to have your ionic application in more than one languages.

In this part of the blog, we will be going to explain how you can include translations facility to your application.

We use for translation language ngx-translate npm plugin.

Ngx-translate:

It is an npm plugin that is used for translate the language and switching languages.

First of all, we need to install the above mentioned plugin in the application using the below mentioned command.

$ npm install @ngx-translate/core @ngx-translate/http-loader --save

After installing ngx-translate you need to import array in the NgModule of the application.
Below is an example of the app.module.ts file:

import { NgModule } from '@angular/core';
import { TranslateModule } from '@ngx-translate/core';

@NgModule({
  imports: [
    TranslateModule.forRoot()
  ],
Providers:[]
})
export class AppModule{}

Now after injecting the plugin in the module we must know how to use that in application. First of all we need to create multiple json files for each language that you are planning to have in your application. Let’s say for example, you are planning to have two languages English and French in your application then please create two files at the below mentioned path.

/assets/i18n/en.json and /assets/i18n/fr.json
If the i18n folder is not there then please create it at above-mentioned path and then place the json files under it.

Now let’s have a look at how those files will look like from inside.

en.json file:
{
    HELLO:"Hello World"
}
Or 
fr.json file:
{
    HELLO:"Bonjour"
}

Now as we are done with the basic setup of multilingual functionality in our application, Let’s implement it in our component. First, include the injections in app.module.ts file

app.module.ts

import { NgModule } from '@angular/core';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpModule, Http } from '@angular/http';

export function createTranslateLoader(http: Http) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
@NgModule({
  imports: [
    HttpModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [Http]
      }
    })
  ]
})
export class AppModule{}

After implementing above mentioned code we need to use TranslatePipe and TranslateService to translate the language of view file. The TranslatePipe is an angular js pipe.

Below Example suggest how TranslatePipe to translate the language of application:

<h1> {{ 'HELLO' | translate }} </h1>

Note: Make sure this key of is declared in JSON file otherwise it will not translate the value instead it will directly print the key “HELLO” as it is.

Now let’s talk about the TranslateService, it can be used for both, to change the current language of an app and to translate JavaScript values in an application.

To use the TranslateService in your app you must first import it and set the default language.

app.component.ts

import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'page-schedule',
    templateUrl: 'schedule.html'
})
export class SchedulePage {
    constructor(translate: TranslateService) {
        translate.setDefaultLang('en');
    }
}

Here, translate.setDefaultLang(‘en’) is set default language and we change here to language as we added to our project.

Hope this blog helped you feel free to share your feedbacks/queries, also need assistance regarding Ionic App Development then get in touch with us.

Know How To Use SQLite In Ionic 2

Know How To Use SQLite In Ionic 2

Ionic 2

Ionic 2 is the upgraded version of ionic 1 and it has a lot of differences in it than the earlier one. Typescripts are introduced in this as well. Some new components are also included in ionic 2.

Let’s talk about the backend database with ionic 2. Nowadays requirements for offline application is becoming more popular. People want to have a quick and very much accurate application with or without internet connectivity. SQLite is a phenomenon, which can be useful in providing such feature.

SQLite

SQLite is a software library that implements SQL operations using SQL database engine. SQLite is the widely deployed SQL database engine in the world.

SQLite is a local storage for the applications, SQLite is used for storing data similarly we store data in server-side websites using MySQL. SQLite provides the similar functions and queries as we have in MySQL

SQLite provides faster access to the data in an application. One can fetch the data from the server and can save in SQLite database so that later on we can use it from SQLite only because of which application’s performance will good rather than normal application.

Note: SQLite stores its database on the local device so that you can’t find your data in another device also due to this the size of an application is also got increased.

Why we use SQLite 

  • In case you’re unfamiliar with local storage, it is key-value storage within your application.
  • This makes it difficult to query for data when you have a lot of it.
  • Not only is their query difficulties, but there are limitations. And local storage has a limitation of 10MB of data.

These reasons are what makes SQLite a better choice if we compare it against local storage.

Connection with SQLite 

For using SQLite in our application we need to add the SQLite plugin given by Cordova in our ionic v2 application. It can be added via the following:

$ ionic plugin add cordova-sqlite-storage
$ npm install –save @ionic-native/sqlite

pages/home/home.ts

import {Component} from '@angular/core';
import {NavController, Platform} from 'ionic-angular';
import {SQLite} from "ionic-native";
import { AddNote } from '../addnote/addnote';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  public database: SQLite;
  public people: Array<Object>;
  addnote = AddNote;
  public username:any;
  public password:any;
  constructor(private navController: NavController, private platform: Platform) {
      this.platform.ready().then(() => {
          this.database = new SQLite();
          this.database.openDatabase({
            name: "data.db",
             location: "default"
           }).then((data) => {
              this.database.executeSql("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT)", {})
                .then((data) => {
                    console.log("TABLE CREATED: ", data);
                   alert('db and table created ');
                }, (error) => {
                    console.error("Unable to execute sql", error);
                })
            }, (error) => {
                console.error("Unable to open database", error);
            });
      });
  }
  public add() {
    this.database.executeSql("INSERT INTO userdata (firstname, lastname) VALUES ('"+this.firstname+"', '"+this.lastname+"')", []).then((data) => {
            console.log("INSERTED: " + JSON.stringify(data));
            alert(JSON.stringify(data));

        }, (error) => {
            console.log("ERROR: " + JSON.stringify(error.err));
        });
  }
  Public select() {
       this.database.executeSql("SELECT * FROM userdata", []).then((data) => {
           this.people = [];
           if(data.rows.length > 0) {
               for(var i = 0; i < data.rows.length; i++) {
                   this.people.push({firstname: data.rows.item(i).firstname, lastname: data.rows.item(i).lastname});
                 }
           }
       }, (error) => {
           console.log("ERROR: " + JSON.stringify(error));
       });
   }

Here, in the platform.ready() function, we will create a new database and it will store in device, openDatabase() is a function for opening database, it has two cases if the Database does not exist then, it will create the DB and open it and if it already exists then, it will open that one. deleteDatabase() delete the database.  add() function will add the firstname and lastname in userdata table. executeSql() Execute SQL on the opened database.

Note, you must open/create DB first, and ensure it resolved and successfully opened.

pages/home/home.html

<ion-content padding>
  <ion-item>
      <ion-input type="text" name="title"  placeholder="Firstname" [(ngModel)]="firstname"  required></ion-input>
  </ion-item>
  <ion-item>
     <ion-input type="text" placeholder="Lastname" [(ngModel)]="lastname" required></ion-input>
   </ion-item>
<button ion-button (click)="add()">Add</button>  <button ion-button (click)="select()">Select</button>

  <ion-card *ngFor="let peopl of people ">
      
{{peopl.firstname}}
     
{{peopl.lastname}}
  </ion-card> </ion-content>

Note: Access SQLite databases on the device.

Feel free to review this document for more details. Leave your vital feedback and we are readily available for any query resolving. Hope you had a quick solution for your purpose, feel free to Hire our Hybrid App Development service, provider.

Ingenious Ways To Create Audio Player With Ionic

Audio-ionic

Nowadays many applications are having another source of medium to show the information to the users other than text. For example, video and audio. In this article let’s focus on having an audio player in your ionic application. An audio player for Ionic works with HTML5 audio or native audio using Cordova Media plugin. It creates an interface to the Cordova-media plugin including a service that controls Media playback and directives to define the look and feel of the player.

Install dependencies for having audio player

  • Install this module using bower
$ bower install ionic-audio
  • Cordova media plugin
$ ionic plugin add cordova-plugin-media

Note: If your project does not have any platform then, you must add one and make a build if you want to test it on your device. Keep in mind that the plugin which we have installed above depends on a Cordova plugin so the module won’t run locally with ionic serve. However, you can still run the project locally to tune the UI before deploying to the device.

Include Js file in Index.html

 <script type="text/javascript" src="lib/ion-audio/dist/ion-audio.js"></script>

Inject the dependency in your app’s module

 angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ionic-audio'])

Inject this code in view file player UI using directives

 <ion-view view-title="Music Player">   
<ion-content>
    <ion-audio-track track="track">
<div class="list list-inset">
           <div class="item item-thumbnail-left">
                <img src="{{track.art}}">
                <h2>{{track.title}}</h2>
                <p>{{track.artist}}</p>
              <ion-audio-controls>
               <a class="button button-icon icon"          
             ion-audio-play> 
          </a>
                <ion-spinner icon="ripple"></ion-spinner>
              </ion-audio-controls>
           </div>
              <div class="item">
                <ion-audio-progress-bar 
track="track" display-time>
</ion-audio-progress-bar>            
   </div>
</div>
    <ion-audio-track>
      </ion-content>
 </ion-view> 

Here, track=”track” is a UI directive

Ion-audio-track

This is directive which gets us the track information about this audio.Using below mentioned JSON object, you can add the information about the track in an audio player. The interface of the player is defined in ion-audio-track body directive.

$scope.track = {
    url: 'http://www.xyz.com/simple_song.mp3',
    artist: 'abc',
    title: 'xyz',
    art: 'image/album.png'
}

Here, $scope.track.url is the path for audio if you want to play the local song in your android/ios device, just put that audio file in js folder and give the according to a path to that file in the code. Sample example,

 $scope.track = {
        url:'/android_asset/www/assets/mp3/simple_song.mp3',
        artist: 'abc',
        title: 'xyz',
        art: '/android_asset/www/assets/image/album.png'
  }

Use as a global progress bar

If an ion-audio-progress-bar is placed inside the scope of ion-audio-track, it will automatically work and will progress automatically according to the audio goes on. Add a display-info to show the current playing track. Add a display-time to show timing in the track list.

<ion-audio-progress-bar display-time display-info></ion-audio-progress-bar>

Media Manager

Inject MediaManager in your controller if you need to access the currently playing track. For example, in order to stop playback before transitioning to another view any other action:

.controller('MusicCtrl', ['$scope', 'MediaManager', function($scope, MediaManager) {

$state.$on('$ionicView.beforeLeave', function() {
        MediaManager.stop();
    });

Hope you had the quick solution for your purpose, feel free to Hire our Hybrid App Development service, provider.

How To Implement Multiselect Tag Input In Ionic App Development

Implement Multiselect Tag Input

Ionic tagging is most beautiful textbox (component) in the application. Basically, this component is used for filtering the data. In E-commerce application where the user needs to filter data from a large number of categories, we can use this. Some of the examples are Flipkart, Amazon, Snapdeal etc.

The Tagging component looks like autocomplete textbox but the major difference is that we can’t  select multiple tags in autocomplete textbox. Here, we can select multiple types. The ideal example is the mailbox where we need to send an email to more than one person at that time we can use this.

Ionic (Hybrid App Development) is providing such facility that we can integrate one simple plugin in the application for fulfilling the tagging feature need. The name of the plugin is ui-select2. There is one more plugin using which gives similar functionality named Tag Input.

Installation Methods: Below are the two methods for installing above mentioned plugins.

Npm
    $ npm install ui-select
    $ npm install ng-tags-input --save
bower

    $ bower install angular-ui-select 
    $ bower install ng-tag-input --save 

Installation ui-select

Let’s start with first plugin ui-select: After the installation of plugin, please import js files using below mentioned code in index.html

<script src="lib/select2/select2.js"></script>
<script src="lib/angular-ui-select2/src/select2.js"></script>
<link rel="stylesheet" type="text/css" href="lib/select2/select2.css">

Now take a field in your view (.html) file.

<input type="hidden" ui-select2="select2Options" ng-model="listData.list_of_string">

Review the attribute

ui-select2="select2Options"

It will empower you to get the multiple values in your text field instead of comma separated list you will have tagging kind of look and feel. Once accessed using model value in the controller you will get an array instead of comma separated string value. The look and feel of input tags are because of CSS you have imported in the index.html file. You can always override that CSS by using your own scss in your application to match it with your application theme. You can also create new tags as well while entering non-existing data in the field and just hit enter or GO button from the device.

Js File in controller

Now, as we got all the required libraries with us we need to start coding and for that first, we need to add the dependency in the controller file using below mentioned code.

angular.module('myModule', ['ui.select']);

You can always use strings of tags or bind an array to your tags. But we suggest you to go with Tags as it will give you the power of setting ids to each element of the array so that you can later refer it easily.

$scope.list_of_string_data= {
       0:'Amsterdam',
       1:'Washington',
       3:'Sydney',
       4:'Beijing',
       5:'Cairo'
};

 $scope.select2Options = {
        'multiple': true,
        'simple_tags': true,
        'tags':$scope.list_of_string_data
 };
Here, We will create object store in tag in input tags.
Installation ui-tag-input (“tag input”) Now let’s talk about another plugin ui-tag-input
After the installation of plugin, please import js files using below-mentioned code in index.html
<script src="angular.js"></script>
<script src="ng-tags-input.js"></script>
<link rel="stylesheet" type="text/css" href="ng-tags-input.css">
 Now take a field in your view (.html) file.
<tags-input ng-model="tags">
        <auto-complete source="loadTags($query)"></auto-complete>
 <p>Model: {{tags}}</p>
</tags-input>

The Plugin is rich enough to provide its own directive for tagging facility.Js File in controllerNow, as we got all the required libraries with us we need to start coding and for that first, we need to add the dependency in the controller file using below mentionedcode.
angular.module('myModule', ['ngTagsInput'])

app.controller('MainCtrl', function($scope) {
  $scope.tags = [
    { text: 'abc' },
    { text: 'xyz' },
    { text: 'pqr' }
  ];
});
Here, we will create default tag in an input field and tags would be ‘abc’,’XYZ’,’PQR’.
We can access this information through model associated with the field in view inside the controller file. This plugin also provides data in array format like the former one.
Hope this article has helped you to get the tagging feature in your application.