An Introduction Of HMS Location Kit using Ionic Framework ( Cross Platform )
Introduction
One of the unique features of mobile applications is location awareness. Mobile users take their devices with them everywhere, and adding location awareness to our app offers users a more contextual experience. The Huawei Location kit facilitate adding location awareness to our app with automated location tracking, geofencing, and activity recognition/identification.
HMS Location Kit Services
1. Fused Location
2. Activity Identification
3. Geofence
Ionic Framework
Ionic Framework is an open source UI toolkit for building performant, high-quality mobile and desktop apps using web technologies such as HTML, CSS, and JavaScript with integrations for popular frameworks like Angular and React.
Think of Ionic as the front-end UI framework that handles all of the look and feel and UI interactions your app needs in order to be compelling. Unlike a responsive framework, Ionic comes with very native-styled mobile UI elements and layouts that you’d get with a native SDK on Android or iOS but didn’t really exist before on the web.
Since Ionic is an HTML5 framework, it needs a native wrapper like Cordova or Capacitor in order to run as a native app.
Here we will use Ionic framework with Angular and Capacitor as native wrapper.
Demo
Prerequisite
1) Must have a Huawei Developer Account.
2) Must have a Huawei phone with HMS 4.0.0.300 or later.
3) Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
4) Must install node in the system
5) Must install Ionic in the system using below command:
npm install -g @ionic/cli
Things need to be done
1) Generating a Signing Certificate Fingerprint. For generating the SHA key, refer this article.
2) Create an app in the Huawei AppGallery connect and enable Location Kit in Manage Api section.
3) Provide the SHA Key in App Information Section.
4) Provide storage location.
5) Download the agconnect-services.json and store it somewhere on our computer.
6) Create a blank Ionic Project using below command:
ionic start Your_Application_Name blank — type=angular
7) Run the following command in the root directory of your Ionic project to install HMS Location kit it through npm.
npm install @hmscore/cordova-plugin-hms-location
8) If you want full Ionic support with code completion etc., install @ionic-native/core in your project.
npm install @ionic-native/core — save-dev
9) Run the following command to copy the “ionic/dist/hms-ml” folder from library to “node_modules/@ionic-native” folder under your Ionic project.
cp node_modules/@hmscore/cordova-plugin-hms-location/ionic/dist/hms-location node_modules/@ionic-native/ -r
10) Run the following command to compile the project:
ionic build
npx cap init [appName] [appId]
Where appName is the name of your app, and appId is package_name in your agconnect-services.json file (ex: com.example.app).
11) Run the following command to add android platform to your project:
ionic capacitor add android
12) Make sure your project has a build.gradle file with a maven repository address and agconnect service dependencies as shown below:
13) Add the Signing certificate configuration to the build.gradle file in the app directory as show below:
14) Add plugin to the build.gradle file in the app directory as show below:
apply plugin: ‘com.android.application’
apply plugin: ‘com.huawei.agconnect’
15) Add site kit service implementation into to dependencies section of build.gradle file in the app directory as show below:
dependencies {
…
implementation ‘com.huawei.hms:location:5.0.4.300’
}
16) Add agconnect-services.json and signing certificate jks file to the app directory in your Android project as show below:
17) To update dependencies, and copy any web assets to your project, run the following code:
npx capacitor sync
Intialize Location
We need to initialize location, fused location and activity identification as shown below:
ngOnInit() {this.hmsLocationKit.init();this.hmsFusedLocation.init();this.hmsActivityIdentification.init();}
ngOnInit() function is a life cycle hook called by Angular2 to indicate that Angular is done creating the component.
Permission Needed
<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION” />
<uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION"/>
Fused Location
It helps us to obtain device location based on Global Navigation Satellite System, Wi-Fi, and base station location data.
Check For Fused Location Permissions
In order to check fused location permission is there or not, we need to call hasPermission() as shown below:
async checkLocationPermission() {
var res = await this.hmsFusedLocation.hasPermission();
alert(“ HAS PERMISSION : “+res.hasPermission);
}
Request Fused Location Permission
If permission is not provided, we need to ask user to provide fused location service related permissions as shown below:
async requestLocationPermission() {
var result = await this.hmsFusedLocation.requestPermission();
alert(JSON.stringify(result));
}
Checking The Device Location Settings
We much check whether the device settings meet the location requirements before continuously obtaining location information.
Get Last Device Location
As the name implies, we will receive device last known location using the code below:
async getLastLocation(){
var lastLocationResult = await this.hmsFusedLocation.getLastLocation();
alert(JSON.stringify(lastLocationResult));
}
Get Last Device Location With Address
As the name implies, we will receive device last know location with address using the code below:
async getLastLocationWithAddress(){
var lastLocationWithAddressResult = await this.hmsFusedLocation.getLastLocationWithAddress(this.getLocationRequest());
alert(JSON.stringify(lastLocationWithAddressResult));
}
Enable/Disable Mock mode & Mock location
This functionality helps us to set the device location manually. We can also enable or disable mock mode. Whenever we need user last location it will always provide user mock location.
Activity Identification & Conversion Service
Using acceleration sensor, cellular network information, and magnetometer it helps us to identify user motion status like walking, running etc.
Request Activity Identification Permission
We need to ask detect motion status permission from user in order to work with activity identification service as shown below:
async requestActivityPermission() {
var result = await this.hmsActivityIdentification.requestPermission();
alert(JSON.stringify(result));
}
Create Activity Identification
Here we check the status of the user such as walking, bicycling or motionless. This method will help us to set the interval in milliseconds for detecting activity identification updates. Larger values will result in fewer activity detections, and smaller values will result in more activity detections.
async createActivityIdentificationUpdates(){var activityIdentificationUpdates = await this.hmsActivityIdentification.createActivityIdentificationUpdates(2000);this.activityIdentificationUpdateRequests.push(activityIdentificationUpdates.requestCode);alert(JSON.stringify(activityIdentificationUpdates));}
Register Activity Identification
We can register activity identification by using below code:
registerActivityIdentificationUpdates() {window.registerHMSEvent(Events.ACTIVITY_IDENTIFICATION_RESULT, (result) =>// alert(JSON.stringify(result)));console.log(“ACTIVITY IDENTIFICATION UPDATES IS REGISTERED”));}
Delete Activity Identification
If we wish to remove or stop activity identification then we need to use below code:
async deleteActivityIdentificationUpdates(){this.activityIdentificationUpdateRequests.forEach(async requestCode => {var res = await this.hmsActivityIdentification.deleteActivityIdentificationUpdates(requestCode);alert(“REQUEST CODE: “+ requestCode + “ is “ + res + “, MEANS DELETED…” );});this.activityIdentificationUpdateRequests = [];}
Create Activity Conversion
Here we check whether the user status change for example whether user entered walking mode or exit walking mode. The interval for detecting activity conversion updates is 5 seconds when the screen is on and 200 seconds when the screen is off.
Register Activity Conversion
We can register activity conversion by using below code:
registerActivityConversionUpdates() {window.registerHMSEvent(this.hmsActivityIdentification.Events.ACTIVITY_CONVERSION_RESULT, (result) =>// alert(JSON.stringify(result)));console.log(“ACTIVITY CONVERSION UPDATES IS REGISTERED”));}
Remove Activity Conversion
If we wish to remove the id or updated fetched when creating activity conversion then we need to use below code:
async deleteActivityConversionUpdates(){this.activityConversionUpdateRequests.forEach(async requestCode => {var res = await this.hmsActivityIdentification.deleteActivityConversionUpdates(requestCode);alert(“REQUEST CODE: “+ requestCode + “ is “ + res + “, MEANS DELETED…” );});this.activityConversionUpdateRequests = [];}
Geofence Service
One use case which came to my mind is when we need to track a person location. If the person location is under the diameter of geofence location then a notification will be triggered. Another user case we can use this service is when a prisoner escape from a jail then a notification will be trigger and sent to all police station.
In a simple way Geofence service allows us to set an interested area through using the API so that our app can receive a notification when a specified action such as leaving, entering, or staying in the area occurs. Below you can find the code of creating, registering and deleting Geofence service:
Run application
Now we can run the application using the following command on visual studio terminal:
ionic capacitor run android
Tips & Tricks
1) Make sure to add HMSFusedLocation, HMSActivityIdentification, HMSGeofence and HMSLocationKit as provider in app.module.ts file otherwise No Provider Error will occur also make sure to import the same as well.
2) To work with mock location, we need to navigate to device settings and choose developer options. Under developer options we need to navigate to select mock location app. Now choose the app for mock location.
Conclusion
We learn how to integrate HMS Location Kit in Ionic Project. Using HMS Location kit we can create application such as tourism application, restaurant based application and so on. I hope this article will be very useful to you in order to create wonderful application using Ionic.
Feel free to comment, share and like the article. Also you can follow me to get awesome article like this every week.