[Huawei Developers] Efnan Akkus:
[IMG="image1"]https://miro.medium.com/max/1050/1*zwdgn3vkI0AK7MbGmuq9Rw.png[/IMG]

Introduction

This article covers, how to integrate Cordova Hms Location Kit to a Cordova application.

Cordova Hms Location Kit supports services listed below

Fused Location Service

Activity Identification Service

Geofence Service

There are several number of uses cases of these services, you can combine them or just use them to create different functionalities in your app. For basic understanding, please read uses cases from here.

Prerequisites

Step 1

Prepare your development environment using this guide.

After reading this guide you should have Cordova Development Environment setted up, Hms Core (APK) installed and Android Sdk installed.

Step 2

Configure your app information in App Gallery by following this guide.

After reading this guide you should have a Huawei Developer Account, an App Gallery app, a keystore file and enabled Location kit service from AppGallery.

Integrating Cordova Hms Location Kit

To download or use HUAWEI Location Kit, you must agree to Huawei Developer Service Agreement, HUAWEI APIs Use Agreement, and AppGallery Connect Data Processing Addendum. You understand and undertake that downloading or using said HUAWEI Location Kit shall be deemed that you have agreed to all the preceding agreements, and you will fulfill and assume the legal responsibilities and obligations in accordance with said agreements.

Warning : Please make sure that, prerequisites part successfully completed.

Step 1

Add Android platform to your project if you haven’t yet.

cordova platform add android

Step 2

Check Cordova requirements with following command.

cordova requirements

Step 3

You can either install the plugin thorough npm or by downloading from downloads page, Cordova Location Plugin. Run the following command in the root directory of your Cordova project to install it through npm.

cordova plugin add @hms-core/cordova-plugin-hms-location

Run the following command in the root directory of your Cordova project to install it manually after downloading the plugin.

cordova plugin add <CORDOVA_PLUGIN_PATH>

Step 4

Check whether the Cordova Location Plugin is successfully added to “plugins” folder in the root directory of the Cordova project.

[IMG="image5"]https://miro.medium.com/max/444/1*ap_JrfB3FHeiEkcFTV8_ig.png[/IMG]

Step 5

Open build.gradle file in project-dir > android folder.

Go to buildscript > repositories and allprojects > repositories, and configure the Maven repository address.

buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}

Go to buildscript > dependencies and add dependency configurations.

buildscript {
dependencies {
classpath 'com.huawei.agconnect:agcp:1.2.1.301'
}
}

Step 6

Open build.gradle file which is located under project.dir > android > app directory.

Add the AppGallery Connect plug-in dependency to the file header.

The apply plugin: ‘com.huawei.agconnect’ configuration must be added after the apply plugin: ‘com.android.application’ configuration.

The minimum Android API level (minSdkVersion) required for Location Kit is 19.

Configure build dependencies of your project.

dependencies {
...
implementation 'com.huawei.agconnect:agconnect-core:1.0.0.301'
}

Create An Application for Cordova Location Kit

In the application we will do, the user will be able to view his/him last location and receive a notification when he/she leaves the area he/she has determined.

So, we need to initialize HMSFusedLocation, HMSLocationKit, HMSGeofence services in onCreate method.

Step 1

function onDeviceReady() {
// Initialize LocationKit
HMSLocationKit.init();
HMSFusedLocation.init();
HMSGeofence.init();

// Device ready effect
var parentElement = $('deviceready');
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');

listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
};

An App can use the HUAWEI Location Kit service API to obtain the last known location of a device. In most cases, the last known location is the current location of the device. The following is the sample code for calling the getLastLocation() method to obtain the last known location.

Note That : Before running this code snippet please check for your app permissions.

Step 2

$('requestPermission').onclick = async () => {
try {
const permissionResult = await HMSFusedLocation.requestPermission();
console.log({permissionResult});
$('requestPermissionResult').innerHTML = JSON.stringify(permissionResult, null, 1);
} catch (ex) {
$('requestPermissionResult').innerHTML = JSON.stringify(ex, null, 1);
}

};

$('hasPermission').onclick = async () => {
try {
const hasPermissionResult = await HMSFusedLocation.hasPermission();
console.log({hasPermissionResult});
$('hasPermissionResult').innerHTML = JSON.stringify(hasPermissionResult, null, 1);
} catch (ex) {
$('hasPermissionResult').innerHTML = JSON.stringify(ex, null, 1);
}

};

Step 3

const $ = (x) => document.getElementById(x);

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
// Initialize LocationKit
HMSLocationKit.init();
HMSFusedLocation.init();
HMSGeofence.init();

// Device ready effect
var parentElement = $('deviceready');
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');

listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
};

const newLocationRequest = () => { return {
id: "locationRequest" + Math.random() * 10000,
priority:
HMSFusedLocation.PriorityConstants.PRIORITY_HIGH_ACCURACY,
interval: 3,
numUpdates: 1,
fastestInterval: 1000.0,
expirationTime: 1000.0,
expirationTimeDuration: 1000.0,
smallestDisplacement: 0.0,
maxWaitTime: 1000.0,
needAddress: false,
language: "en",
countryCode: "en",
}};

$('getLastLocation').onclick = async () => {
try {
const lastLocation = await HMSFusedLocation.getLastLocation();
console.log({lastLocation});
$('getLastLocationResult').innerHTML = JSON.stringify(lastLocation, null, 1);
} catch (ex) {
$('getLastLocationResult').innerHTML = JSON.stringify(ex, null, 1);
}
};

$('requestPermission').onclick = async () => {
try {
const permissionResult = await HMSFusedLocation.requestPermission();
console.log({permissionResult});
$('requestPermissionResult').innerHTML = JSON.stringify(permissionResult, null, 1);
} catch (ex) {
$('requestPermissionResult').innerHTML = JSON.stringify(ex, null, 1);
}

};

$('hasPermission').onclick = async () => {
try {
const hasPermissionResult = await HMSFusedLocation.hasPermission();
console.log({hasPermissionResult});
$('hasPermissionResult').innerHTML = JSON.stringify(hasPermissionResult, null, 1);
} catch (ex) {
$('hasPermissionResult').innerHTML = JSON.stringify(ex, null, 1);
}

};

$('getLocationAvailability').onclick = async () => {
try {
const locationAvailability = await HMSFusedLocation.getLocationAvailability();
console.log({locationAvailability});
$('getLocationAvailabilityResult').innerHTML = JSON.stringify(locationAvailability, null, 1);
} catch (ex) {
$('getLocationAvailabilityResult').innerHTML = JSON.stringify(locationAvailability, null, 1);
}

};

$('getLastLocationWithAddress').onclick = async () => {
try {
const getLastLocationWithAddressResult = await HMSFusedLocation.getLastLocationWithAddress(newLocationRequest());
console.log({getLastLocationWithAddressResult});
$('getLastLocationWithAddressResult').innerHTML = JSON.stringify(getLastLocationWithAddressResult, null, 1);
} catch (ex) {
$('getLastLocationWithAddressResult').innerHTML = JSON.stringify(ex, null, 1);
}

};

$('createGeofenceList').onclick = async () => {
const geofence1 = {
longitude: 29.117645,
latitude: 41.012429,
radius: 2.0,
uniqueId: 'geofence' + Math.random() * 10000,
conversions: 1,
validContinueTime: 10000.0,
dwellDelayTime: 10,
notificationInterval: 1,
};

const geofence2 = {
longitude: 41.0,
latitude: 27.0,
radius: 340.0,
uniqueId: 'geofence' + Math.random() * 10000,
conversions: 2,
validContinueTime: 1000.0,
dwellDelayTime: 10,
notificationInterval: 1,
};
try {
const createGeofenceListResult = await HMSGeofence.createGeofenceList(
[geofence1],
HMSGeofence.GeofenceRequestConstants.ENTER_INIT_CONVERSION,
HMSGeofence.GeofenceRequestConstants.COORDINATE_TYPE_WGS_84
);
console.log({createGeofenceListResult});
$('createGeofenceListResult').innerHTML = JSON.stringify(createGeofenceListResult, null, 1);
} catch (ex) {
$('createGeofenceListResult').innerHTML = JSON.stringify(ex, null, 1);
}

};

$('registerGeofenceUpdates').onclick = async () => {
registerHMSEvent(HMSGeofence.Events.GEOFENCE_RESULT, (result) => {
console.log('new geofence update');
$('geofenceUpdateResult').innerHTML = JSON.stringify(result, null, 1);
});

};

Test the Location Kit App

Run the application.

cordova run android

Press “Get Last Location” button.

Wait for the result.

Here it comes. You will see your last location on screen.

[IMG="im"]https://miro.medium.com/max/996/1*jexUjawK4bKm1ygiazCNGw.png[/IMG]

Conclusion

In this article, we integrated and used Cordova Hms Location Kit to our application. You can enrich your application by integrating this useful and simple to use kit into your applications.

You can write comments for your questions.

Related Links

Thanks to Furkan Aybastı for this article.