# JSB Location

## Contents

- [1. Introduction](#1-introduction)
- [2. Installation Guide](#2-installation-guide)
    - [Creating a Project in App Gallery Connect](#creating-a-project-in-appgallery-connect)
    - [Configuring the Signing Certificate Fingerprint](#configuring-the-signing-certificate-fingerprint)
    - [React-Native Integration](#react-native-integration)
    - [Cordova Integration](#cordova-integration)
    - [Ionic Integration](#ionic-integration)
        - [Ionic with Cordova Runtime](#ionic-with-cordova-runtime)
        - [Ionic with Capacitor Runtime](#ionic-with-capacitor-runtime)
    - [Configure Permissions](#configure-permissions)
- [3. API Reference](#3-api-reference)
    - [HMSLocation](#hmslocation)
        - [FusedLocationService](#fusedLocationService)
    - [Data Types](#data-types)
    - [Constants](#constants)
        
- [4. Configuration and Description](#4-configuration-and-description)
- [5. Questions or Issues](#5-questions-or-issues)
- [6. Licensing and Terms](#6-licensing-and-terms)

## 1. Introduction

JSSDK enables communication between HUAWEI Location Kit and React Native, Cordova and Ionic platforms. This plugin exposes all capabilities provided by HUAWEI Location Kit. Detailed information about data types, constants and methods provided by this document.

## 2. Installation Guide

### Creating a Project in AppGallery Connect

Creating an app in AppGallery Connect is required in order to communicate with the Huawei services. To create an app, perform the following steps:

**Step 1.** Sign in to [AppGallery Connect](https://developer.huawei.com/consumer/en/service/josp/agc/index.html) and select **My projects**.

**Step 2.** Select your project from the project list or create a new one by clicking the **Add Project** button.

**Step 3.** Go to **Project Setting** > **General information**, and click **Add app**.
If an app exists in the project and you need to add a new one, expand the app selection area on the top of the page and click **Add app**.

**Step 4.** On the **Add app** page, enter the app information, and click **OK**.

- A signing certificate fingerprint is used to verify the authenticity of an app when it attempts to access an HMS Core service through the HMS Core SDK. Before using HMS Core (APK), you must locally generate a signing certificate fingerprint and configure it in AppGallery Connect. Ensure that the JDK has been installed on your computer.

### Configuring the Signing Certificate Fingerprint

**Step 1.** Obtain the signature file that generated in [Generating a Signing Certificate](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#3) section.

**Step 2.** Go to **Project Setting > General information**. In the **App information** field, click the icon next to SHA-256 certificate fingerprint, and enter the obtained **SHA256 certificate fingerprint**.

**Step 3.** After completing the configuration, click check mark.

### React-Native Integration

**Step 1:** Sign in to [AppGallery Connect](https://developer.huawei.com/consumer/en/service/josp/agc/index.html) and select **My projects**.

**Step 2:** Find your app project, and click the desired app name.

**Step 3:** Go to **Project Setting** > **General information**. In the **App information** section, click **agconnect-service.json** to download the configuration file.

**Step 4:** Create a React Native project if you do not have one.

**Step 5:** Copy the **agconnect-service.json** file to the **android/app** directory of your React Native project.

**Step 6:** Copy the signature file that generated in [Generating a Signing Certificate](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#3) section, to the android/app directory of your React Native project.

**Step 7:** Check whether the **agconnect-services.json** file and signature file are successfully added to the **android/app** directory of the React Native project.

**Step 8:** Open the **AndroidManifest.xml** file, add the following lines, and replace the value **<app_id>** with the value you found in the **agconnect-services.json** file.

```xml
<application>
...
     <meta-data
            android:name="com.huawei.hms.client.appid"
            android:value="appid=<app_id>" />
</application>
```

**Step 9:** Open the **build.gradle** file in the **android** directory of your React Native project.

- Go to **buildscript** then configure the Maven repository address and agconnect plugin for the HMS SDK.

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

  dependencies {        
    /*          
      * <Other dependencies>        
      */   
    classpath 'com.huawei.agconnect:agcp:1.4.2.301'    
  }
}
```

- Go to **allprojects** then configure the Maven repository address for the HMS SDK.

```groovy
allprojects {
  repositories {
    /*          
      * <Other repositories>        
      */  
    maven { url 'https://developer.huawei.com/repo/' }
  }
}
```

**Step 10:** Open the **build.gradle** file in the **android/app** directory of your React Native project.

- Package name must match with the **package_name** entry in **agconnect-services.json** file.

```groovy
defaultConfig {
  applicationId "<package_name>"
  minSdkVersion 19
  /*
   * <Other configurations>
   */
}
```

```groovy
android {
  /*
   * <Other configurations>
   */

  signingConfigs {
    config {
      storeFile file('<keystore_file>.jks')
      storePassword '<keystore_password>'
      keyAlias '<key_alias>'
      keyPassword '<key_password>'
    }
  }

  buildTypes {
    debug {
      signingConfig signingConfigs.config
    }
    release {
      signingConfig signingConfigs.config
      minifyEnabled enableProguardInReleaseBuilds
      ...
    }
  }
}
```

**Step 11:** Open the **build.gradle** file in the **android/app** directory of your React Native project.

- Configure build dependencies.

```groovy
buildscript {
  ...
  dependencies {
    /*
    * <Other dependencies>
    */
    implementation ('com.huawei.hms:rn-adapter:5.2.0.300'){
        exclude group: 'com.facebook.react'
    } 
    ...    
  }
}
```

**Step 12:**  Import the following class to the **MainApplication.java** file of your project.

```java
import com.huawei.hms.jsb.adapter.rn.RnJSBReactPackage;
```

Then, add the **RnJSBReactPackage()** to your **getPackages** method. In the end, your file will be similar to the following:

```java
@Override
protected List<ReactPackage> getPackages() {
    List<ReactPackage> packages = new PackageList(this).getPackages();
    packages.add(new RnJSBReactPackage()); // <-- Add this line 
    return packages;
}
...
```

**Step 13:**  Download js-sdk using command below.

```bash
npm i @hmscore/hms-js-location
```

**Step 14:**  Import **HMSLocation** in App.js as following line.

```js
import HMSLocation from "@hmscore/hms-js-location";
```

**Step 15:**  Don't forget to add init function before calling HMSLocation functions.

```js
HMSLocation.init(NativeModules, DeviceEventEmitter);
```

**Step 16:**  Run your project.

- Run the following command to the project directory.

```bash
react-native run-android  
```

### Cordova Integration

**Step 1:** Install Cordova CLI if haven't done before.

```bash
npm install -g cordova
```

**Step 2:** Create a new Cordova project or use the existing one.

- To create new Cordova project, you can use **`cordova create path [id [name [config]]] [options]`** command. For more details please follow [CLI Reference - Apache Cordova](https://cordova.apache.org/docs/en/latest/reference/cordova-cli/index.html#cordova-create-command).

**Step 3:** Update the widget **`id`** property which is specified in the **`config.xml`** file. It must be same with **package_name** value of the **`agconnect-services.json`** file.

**Step 4:** Add the **Android platform** to the project if haven't done before.

```bash
cordova platform add android
```

**Step 5:**  Download plugin using command below.

```bash
cordova plugin add @hmscore/hms-js-location
```

**Step 6:** Copy **`agconnect-services.json`** file to **`<project_root>/platforms/android/app`** directory.

**Step 7:** Add **`keystore(.jks)`** and **`build.json`** files to your project's root directory.

- You can refer to 3rd and 4th steps of [Generating a Signing Certificate](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#2) Codelab tutorial page for generating keystore file.

- Fill **`build.json`** file according to your keystore information. For example:

    ```json
    {
        "android": {
            "debug": {
                "keystore": "<keystore_file>.jks",
                "storePassword": "<keystore_password>",
                "alias": "<key_alias>",
                "password": "<key_password>"
            },
            "release": {
                "keystore": "<keystore_file>.jks",
                "storePassword": "<keystore_password>",
                "alias": "<key_alias>",
                "password": "<key_password>"
            }
        }
    }
    ```

**Step 8:**  Import the following class to the **MainActivity.java** file of your project. You can find this file in **`platforms/android/app/src/main/java/<your_package_name>`** directory.

```java
import com.huawei.hms.jsb.adapter.cordova.CordovaJSBInit;
```

**Step 9:** In the same file, add **CordovaJSBInit.initJSBFramework(this)** line after the **super.onCreate(savedInstanceState)** method call.

- In the end, your file will be similar to the following:

    ```java
    ...

    import com.huawei.hms.jsb.adapter.cordova.CordovaJSBInit;

    public class MainActivity extends CordovaActivity
    {
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            CordovaJSBInit.initJSBFramework(this);

            ...
        }
        ...
    }
    ```

**Step 10:** Open the **AndroidManifest.xml** file, add the following lines, and replace the value **<app_id>** with the **app_id** value that can be found in the **agconnect-services.json** file.

```xml
<application>
...
     <meta-data
            android:name="com.huawei.hms.client.appid"
            android:value="appid=<app_id>" />
</application>
```

**Step 11:**  Run the app

  ```bash
  cordova run android
  ```

### Ionic Integration

Install Ionic CLI and other required tools if haven't done before.

```bash
npm install -g @ionic/cli cordova-res native-run
```

#### Ionic with Cordova Runtime

**Step 1:** Enable the **Cordova integration** if haven't done before.

```bash
ionic integrations enable cordova
```

**Step 2:** Update the widget **`id`** property which is specified in the **`config.xml`** file. It must be same with **package_name** value of the **`agconnect-services.json`** file.

**Step 3:** Add the **Android platform** to the project if haven't done before.

```bash
ionic cordova platform add android
```

**Step 4:** Install `HMS Location Plugin` to the project.

```bash
ionic cordova plugin add @hmscore/hms-js-location
```

**Step 5:** Copy **`agconnect-services.json`** file to **`<project_root>/platforms/android/app`** directory.

**Step 6:** Add **`keystore(.jks)`** and **`build.json`** files to your project's root directory.

- You can refer to 3rd and 4th steps of [Generating a Signing Certificate](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#2) Codelab tutorial page for generating keystore file.

- Fill **`build.json`** file according to your keystore information. For example:

    ```json
    {
        "android": {
            "debug": {
                "keystore": "<keystore_file>.jks",
                "storePassword": "<keystore_password>",
                "alias": "<key_alias>",
                "password": "<key_password>"
            },
            "release": {
                "keystore": "<keystore_file>.jks",
                "storePassword": "<keystore_password>",
                "alias": "<key_alias>",
                "password": "<key_password>"
            }
        }
    }
    ```

**Step 7:**  Import the following class to the **MainActivity.java** file of your project. You can find this file in **`platforms/android/app/src/main/java/<your_package_name>`** directory.

```java
import com.huawei.hms.jsb.adapter.cordova.CordovaJSBInit;
```

**Step 8:** In the same file, add **CordovaJSBInit.initJSBFramework(this)** line after the **super.onCreate(savedInstanceState)** method call.

- In the end, your file will be similar to the following:

    ```java
    ...

    import com.huawei.hms.jsb.adapter.cordova.CordovaJSBInit;

    public class MainActivity extends CordovaActivity
    {
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            CordovaJSBInit.initJSBFramework(this);

            ...
        }
        ...
    }
    ```

**Step 9:** Open the **AndroidManifest.xml** file, add the following lines, and replace the value **<app_id>** with the **app_id** value that can be found in the **agconnect-services.json** file.

```xml
<application>
...
     <meta-data
            android:name="com.huawei.hms.client.appid"
            android:value="appid=<app_id>" />
</application>
```

**Step 10:** Run the application.

```bash
ionic cordova run android --device
```

#### Ionic with Capacitor Runtime

**Step 1:** Enable the **Capacitor integration** if haven't done before.

```bash
ionic integrations enable capacitor
```

**Step 2:** Initialize **Capacitor** if haven't done before. It must be same with **package_name** value of the **`agconnect-services.json`** file.

```bash
npx cap init [appName] [appId]
```

- For more details please follow [Initialize Capacitor with your app information](https://capacitorjs.com/docs/getting-started/with-ionic#initialize-capacitor-with-your-app-information).

**Step 3:** Install `HMS Location plugin` to the project.

```bash
npm install @hmscore/hms-js-location
```

**Step 4:** Build Ionic app to generate resource files.

```bash
ionic build
```

**Step 5:** Add the **Android platform** to the project.

```bash
npx cap add android
```

**Step 6:** Copy **`keystore(.jks)`** and **`agconnect-services.json`** files to **`<project_root>/android/app`** directory.

- You can refer to 3rd and 4th steps of [Generating a Signing Certificate](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#2) Codelab tutorial page for generating keystore file.

**Step 7:** Open the **`build.gradle`** file in the **`<project_root>/android/app`** directory.

- Add `signingConfigs` entry to the **android** section and modify it according to your keystore.

- Enable `signingConfig` configuration for **debug** and **release** flavors.

```groovy
...

android {

    ...

    // Modify signingConfigs according to your keystore
    signingConfigs {
        config {
            storeFile file('<keystore_file>.jks')
            storePassword '<keystore_password>'
            keyAlias '<key_alias>'
            keyPassword '<key_password>'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.config // Enable signingConfig for debug flavor
        }
        release {
            signingConfig signingConfigs.config // Enable signingConfig for release flavor
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
...

apply plugin: 'com.huawei.agconnect' // Apply com.huawei.agconnect plugin. This line must be added to the end of the file.


```

**Step 8:** Open the **`build.gradle`** file in the **`<project_root>/android`** directory. Add **Huawei's maven repositories** and **agconnect classpath** to the file.

```groovy
buildscript {
    repositories {
        /*
            <Other repositories>
        */
        maven { url 'https://developer.huawei.com/repo/' }
    }
    dependencies {
        /*
            <Other dependencies>
        */
        classpath 'com.huawei.agconnect:agcp:1.4.2.301'
    }
}

/*
    <Other build.gradle entries>
*/

allprojects {
    repositories {
        /*
            <Other repositories>
        */
        maven { url 'https://developer.huawei.com/repo/' }
    }
}
```

**Step 9:**  Import the following class to the **MainActivity.java** file of your project. You can find this file in **`android/app/src/main/java/<your_package_name>`** directory.

```java
import com.huawei.hms.js.location.HMSLocation;
```

**Step 10:** In the same file, add **add(HMSLocation.class);** line to the **ArrayList**.

- In the end, your file will be similar to the following:

    ```java
    ...

    import com.huawei.hms.js.location.HMSLocation;

    public class MainActivity extends BridgeActivity
    {
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            // Initializes the Bridge
            this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
                // Additional plugins you've installed go here
                add(HMSLocation.class);
            }});
            ...
        }
        ...
    }
    ```

**Step 11:** Open the **AndroidManifest.xml** file, add the following lines, and replace the value **<app_id>** with the **app_id** value that can be found in the **agconnect-services.json** file.

```xml
<application>
...
     <meta-data
            android:name="com.huawei.hms.client.appid"
            android:value="appid=<app_id>" />
</application>
```

**Step 12:** Updates dependencies, and copy any web assets to your project.

```bash
npx cap sync
```

**Step 13:** Open the project in Android Studio and run it.

```bash
npx cap open android
```

### Configure Permissions

Navigate to **android/app/main/AndroidManifest.xml** file and get required permissions.

```xml
    <!-- For accessing Internet -->
    <uses-permission android:name="android.permission.INTERNET" />

    <!-- The Android OS provides two location permissions: ACCESS_COARSE_LOCATION (approximate location permission) and ACCESS_FINE_LOCATION (precise location permission). -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <!-- If your app needs to continuously locate the device when it runs in the background in Android Q, apply for the ACCESS_BACKGROUND_LOCATION permission -->
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

    <!-- To use the activity identification service in Android Q and later versions, apply for the following permission -->
    <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" /> 

    <!-- To use the activity identification service in versions earlier than Android Q, apply for the following permission -->
    <uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION" />

    <!-- To use the mock location function -->
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
```

## 3. API Reference

### **HMSLocation**

#### Public Method Summary

| Method                                                                        | Return Type                                                                                         | Description                                                                                                                                            |
| ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
|getFusedLocationProviderClient()|`FusedLocationService`|Creates a FusedLocationProviderClient instance.|

### 3.1.2 Public Methods

#### Public Methods

##### getFusedLocationProviderClient()
Creates a FusedLocationProviderClient instance.
###### Return Type
|Type|Description|
|---|---|
|`FusedLocationService`|Main entry class for obtaining the location information.|
###### Sample Code
```js
const fusedLocationClient = HMSLocation.getFusedLocationProviderClient();
```

### FusedLocationService
Fused location class, which is used for interaction during location.
#### Public Method Summary
|Method|Return Type|Description|
|---|---|---|
|checkLocationSettings(locationSettingsRequest)|`Promise<LocationSettingsResult>`|Checks whether relevant location settings are valid.|
|getLastLocation(lastLocationRequest)|`Promise<LocationResult>`|Obtains the available location of the last request.|
|getLocationAvailability()|`Promise<LocationAvailabilityResult>`|Obtains the location availability.|
|getNavigationContextState(type)|`Promise<NavigationResult>`|Obtains the requested navigation type.|
|removeLocationUpdates(uuid)|`Promise<void>`|Removes location updates of the specified request code.|
|requestLocationUpdates(locationUpdateRequest, callback)|`Promise<void>`|Requests location updates. |
|requestLocationUpdatesEx(locationUpdateRequest, callback)|`Promise<void>`|Requests location updates. This is an extended location service API that supports high-precision location and is compatible with common location APIs. This function will take updates only during app is running.|
|setMockLocation(mockLocation)|`Promise<void>`|Sets a specific mock location. You must call the setMockMode(boolean) method and set the flag to true before calling this method.|
|setMockMode(isMockMode)|`Promise<void>`|Sets whether to use the location mock mode. If the value true is passed, the GNSS or network location is not used and the location set through setMockLocation(Location) is directly returned.|

#### Public Methods
##### checkLocationSettings(locationSettingsRequest)
Checks whether relevant location settings are valid.
###### Parameters
|Name|Type|Description|
|---|---|---|
|locationSettingsRequest|LocationSettingsRequest|Request object related to location settings.|
###### Return Type
|Type|Description|
|---|---|
|`Promise<LocationSettingsResult>`|Location setting status.|
###### Sample Code
```js
HMSLocation.getFusedLocationProviderClient().checkLocationSettings({
    requests : [
        {
            priority:HMSLocation.PriorityConstants.PRIORITY_HIGH_ACCURACY,
            interval:10000,
            numUpdates:2147483647,
            fastestInterval:10000,
            expirationTime:3372036854775807.0,
            expirationTimeDuration: 3372036854775807.0,
            isFastestInvervalExplicitlySet : false,
            smallestDisplacement:0.0,
            maxWaitTime:0,
            needAddress:false,
            language:'',
            countryCode:'',
         },
         ...
    ],
    alwaysShow : false,
    needBle : false
})
    .then((res) => { console.log(res) })
    .catch((err) => { console.log(err) });
```

##### getLastLocation()
Obtains the available location of the last request. Instead of proactively requesting a location, this method uses the location cached during the last request.
The value null may be returned to the following scenarios:
- The location function has never been used.
- The location function is disabled.
- The device is restored to factory settings.
  If real-time location is required, you are advised to proactively call requestLocationUpdates instead of getLastLocation. To receive a location once only, you can set numUpdates in LocationRequest to 1.
###### Parameters
|Name|Type|Description|
|---|---|---|
|lastLocationRequest|LastLocationRequest|Request object related to location settings.|
###### Return Type
|Type|Description|
|---|---|
|`Promise<LocationResult>`|Location result object.|
###### Sample Code
```js
HMSLocation.getFusedLocationProviderClient().getLastLocation({
    needAddress : true,
    language : "tr",
    countryCode : "TR"
})
    .then((res) => { console.log(res) })
    .catch((err) => { console.log(err) });
```

##### getLocationAvailability()
Obtains the location availability.
###### Return Type
|Type|Description|
|---|---|
|`Promise<LocationAvailabilityResult>`| Location availability result object.|
###### Sample Code
```js
HMSLocation.getFusedLocationProviderClient().getLocationAvailability()
    .then((res) => { console.log(res) })
    .catch((err) => { console.log(err) });
```

##### getNavigationContextState(type)
Obtains the requested navigation type.
###### Parameters
|Name|Type|Description|
|---|---|---|
|type|HMSLocation.NavigationRequestConstants|An enum value indicated navigation request type.|
###### Return Type
|Type|Description|
|---|---|
|`Promise<NavigationResult>`|Navigation result object.|
###### Sample Code
```js
HMSLocation.getFusedLocationProviderClient().getNavigationContextState(HMSLocation.NavigationRequestConstants.OVERPASS)
    .then((res) => { console.log(res) })    
    .catch((err) => { console.log(err) });
```

##### removeLocationUpdates(uuid)
Removes location updates of the specified request code.
###### Parameters
|Name|Type|Description|
|---|---|---|
|uuid|string| Uuid used in requestLocationUpdates() or requestLocationUpdatesEx().|
###### Return Type
|Type|Description|
|---|---|
|`Promise<void>`||
###### Sample Code
```js
HMSLocation.getFusedLocationProviderClient().removeLocationUpdates('2fc66152-d0bb-4faa-922a-1224f59b6976')
    .then((res) =>{ console.log(res) })
    .catch((err) => { console.log(err) });
```

##### requestLocationUpdates(locationUpdateRequest, callback)
Requests location updates.
###### Parameters
|Name|Type|Description|
|---|---|---|
|locationUpdateRequest|LocationUpdateRequest|An object that contains location update request.|
|callback|function|A callback function which will be called when location update is occurred.|
###### Return Type
|Type|Description|
|---|---|
|`Promise<void>`||
###### Sample Code
```js
HMSLocation.getFusedLocationProviderClient().requestLocationUpdates({
    locationRequest : {
        priority:HMSLocation.PriorityConstants.PRIORITY_HIGH_ACCURACY,
        interval:10000,
        numUpdates:2147483647,
        fastestInterval:10000,
        expirationTime:3372036854775807.0,
        expirationTimeDuration: 3372036854775807.0,
        isFastestInvervalExplicitlySet : false,
        smallestDisplacement:0.0,
        maxWaitTime:0,
        needAddress:false,
        language:'',
        countryCode:'',
    },
    uuid : '2fc66152-d0bb-4faa-922a-1224f59b6976',
  },
  (result) => {console.log(JSON.stringify(result))}
)
    .then((res) =>{ console.log(res) })    
    .catch((err) => { console.log(err) });
```

##### requestLocationUpdatesEx(locationUpdateRequest,  callback)
Requests location updates. This is an extended location service API that supports high-precision location and is compatible with common location APIs. This function will take updates only during the app is running.
###### Parameters
|Name|Type|Description|
|---|---|---|
|locationUpdateRequest|LocationUpdateRequest|LocationUpdateRequest object.|
|callback|function|A callback function which will be called when location update is occurred.|
###### Return Type
|Type|Description|
|---|---|
|`Promise<void>`||
###### Sample Code
```js
HMSLocation.getFusedLocationProviderClient().requestLocationUpdatesEx({
    locationRequest : {
        priority:HMSLocation.PriorityConstants.PRIORITY_HD_ACCURACY,
        interval:10000,
        numUpdates:2147483647,
        fastestInterval:10000,
        expirationTime:3372036854775807.0,
        expirationTimeDuration: 3372036854775807.0,
        isFastestInvervalExplicitlySet : false,
        smallestDisplacement:0.0,
        maxWaitTime:0,
        needAddress:false,
        language:'',
        countryCode:'',
    },
    uuid : '2fc66152-d0bb-4faa-922a-1224f59b6976',
  },
  (result) => {console.log(JSON.stringify(result))}
)
    .then((res) =>{ console.log(res) })    
    .catch((err) => { console.log(err) });
```

##### setMockLocation(mockLocation)
Sets a specific mock location. You must call the setMockMode(true) function before calling this.
###### Parameters
|Name|Type|Description|
|---|---|---|
|mockLocation|MockLocation|Location object.|
###### Return Type
|Type|Description|
|---|---|
|`Promise<void>`|Empty Promise.|
###### Sample Code
```js
HMSLocation.getFusedLocationProviderClient().setMockLocation(
   {
        mLatitude : 40.59400,
        mLongitude : 29.02918
   }
)
    .then((res) =>{ console.log(res) })
    .catch((err) => { console.log(err) });
```

##### setMockMode(isMockMode)
Sets whether to use the location mock mode. If the value true is passed, the GNSS or network location is not used and the location set through setMockLocation(Location) is directly returned.
###### Parameters
|Name|Type|Description|
|---|---|---|
|isMockMode|boolean|If this parameter is set to true, the mock mode will be used. If this parameter is set to false, the mock mode will not be used.|
###### Return Type
|Type|Description|
|---|---|
|`Promise<void>`|-|
###### Sample Code
```js
HMSLocation.getFusedLocationProviderClient().setMockMode(true)
    .then((res) =>{ console.log(res) })    
    .catch((err) => { console.log(err) });
}
```

### Data Types

#### LastLocationRequest

An object that contains last location request.

|Field|Type|Description|
|---|---|---|
|needAddress|`boolean`|Result contains address information if this field is true.|
|language|`string`|Language code.|
|countryCode|`string`|Country code.|

#### LocationResult

An object that contains location and address result.

|Field|Type|Description|
|---|---|---|
|location|`Location`|An object that contains location information.|
|address|`Address`|An object that contains address information.|

#### Location

An object that contains location information.

|Field|Type|Description|
|---|---|---|
|mLatitude|`number`|Latitude of the current location.|
|mLongitude|`number`|Longitude of the current location.|
|mAltitude|`number`|Altitude of the current location.|
|mSpeed|`number`|Device speed at the current location, in meters per second.|
|mBearing|`number`|Device bearing at the current location, in degrees.|
|mAccuracy|`number`|Horizontal location accuracy, in meters.|
|mTime|`number`|Current timestamp, in milliseconds.|
|mProvider|`boolean`|Location method, for example, network location, GNSS, Wi-Fi, and Bluetooth.|
|mElapsedRealtimeNanos| `number` | Time elapsed since system boot, in nanoseconds.|
|mHorizontalAccuracyMeters|`number`|Horizontal location accuracy, in meters.|
|mVerticalAccuracyMeters|`number`|Vertical location accuracy, in meters.|
|mBearingAccuracyDegrees|`number`|Bearing accuracy at the current location, in degrees.|
|mSpeedAccuracyMetersPerSecond|`number`|Speed accuracy at the current location, in meters per second.|

#### Address

An object that contains address information for location.

|Field|Type|Description|
|---|---|---|
|mCountryName|`string`|Country name.|
|mCountryCode|`string`|Country code.|
|mState|`string`|Administrative region.|
|mCounty|`string`|County that location belongs.|
|mCity|`string`|City name.|
|mStreet|`string`|Street name.|
|mFeatureName|`string`|Feature building of the current location.|
|mPostalCode|`string`|Postal code of the current location.|
|mPhone| `string` |Phone number of the feature building (such as a store or company) of the current location.|
|mUrl|`string`|Website of the feature building (such as a store or company) of the current location.|
|mExtraInfo|`object`|Additional information, which is a key-value pair.|

#### LocationSettingsRequest

An object that contains checking location settings configuration.

|Field|Type|Description|
|---|---|---|
|requests|`LocationRequest[]`|List of LocationRequest objects|
|needBle|`boolean`|Indicates whether BLE scanning needs to be enabled. The options are true (yes) and false (no).|
|alwaysShow|`boolean`|Indicates whether a location is required for the app to continue. The options are true (yes) and false (no).|

#### LocationRequest

An object that contains required information for location request.

|Field|Type|Description|
|---|---|---|
|priority|`HMSLocation.PriorityConstants`|The request priority. If the GNSS location is requested, set priority to 100. If the network location is requested, set priority to 102 or 104. If the location only needs to be passively received instead of being proactively requested, set priority to 105. If high-precision location is requested, set the priority to 200.|
|interval|`number`|The interval for requesting location updates. If the value is 50000, the app will receive a location update every 50 seconds.|
|numUpdates|`number`|The number of location updates. If the value is 3, the app will receive three location updates.|
|fastestInterval|`number`|The shortest interval for requesting location updates. The values of Interval and FastestInterval, whichever is smaller, will be used for requesting location updates.|
|isFastestIntervalExplicitlySet|`boolean`| True if the shortest request interval is used; false otherwise.|
|expirationTime|`number`|The request expiration time since boot, in milliseconds. You can use the SystemClock.elapsedRealtime() method to obtain the number of milliseconds elapsed from the boot time to the current time. If the location update needs to be stopped 200 seconds later, the request expiration time should equal the return result of SystemClock.elapsedRealtime() plus 200000.|
|expirationTimeDuration|`number`|The request expiration duration. Different from expirationTime, the ExpirationDuration parameter is irrelevant to the boot time. If the location update needs to be stopped 200 seconds later, the request expiration duration should be 200000.|
|smallestDisplacement|`number`|The smallest displacement for location updates. If the displacement between two locations is greater than or equal to the specified parameter value, a location update will be sent to the app.|
|maxWaitTime|`number`|The maximum waiting time for location updates, in milliseconds.When the setting takes effect, the time specified by maxWaitTime will be used as the location update period. After the location update time is reached, locations in the period will be returned to the app at a time.|
|needAddress|`boolean`|Indicates to return the address information.|
|language|`string`|The language.|
|countryCode|`string`|The country/region code.|

#### LocationSettingsResult

An object that contains location setting result.

|Field|Type|Description|
|---|---|---|
|locationSettingsStates|`LocationSettingsStates`|Current location-related setting status.|
|statusCheck|`StatusCheck`|Status of the executed function.|

#### StatusCheck

An object that contains status information.

|Field|Type|Description|
|---|---|---|
|statusCode|`number`|Status code.|


#### LocationSettingsStates

An object that contains location settings states.

|Field|Type|Description|
|---|---|---|
|blePresent|`boolean`|Indicates whether the Bluetooth function is available.|
|bleUsable|`boolean`|Indicates whether the Bluetooth function is enabled.|
|gpsPresent|`boolean`|Indicates whether the GPS service is available.|
|gpsUsable|`boolean`|Indicates whether the GPS service is enabled.|
|gnssPresent|`boolean`|Indicates whether the GNSS function is available.|
|gnssUsable|`boolean`|Indicates whether the GNSS function is enabled.|
|locationPresent|`boolean`|Indicates whether HMS Core (APK) has the location permission.|
|locationUsable|`boolean`|Indicates whether the location permission has been assigned to HMS Core (APK).|
|networkLocationPresent|`boolean`|Indicates whether the network location function is available.|
|networkLocationUsable|`boolean`|Indicates whether the network location function is enabled.|
|hmsLocationPresent|`boolean`|Indicates whether HMS Core (APK) has the location permission.|
|hmsLocationUsable|`boolean`|Indicates whether the location permission has been assigned to HMS Core (APK).|

#### LocationAvailabilityResult

An object that contains location availability result.

|Field|Type|Description|
|---|---|---|
|locationAvailability|`LocationAvailability`|Device location availability.|

#### LocationAvailability

An object that contains location availability status codes.

|Field|Type|Description|
|---|---|---|
|locationStatus|`number`|Device location status.|
|cellStatus|`number`|Device mobile cell status.|
|elapsedRealtimeNs|`number`|Elapsed real time.|
|wifiStatus|`number`|Device wifi status.|

#### NavigationResult
|Field|Type|Description|
|---|---|---|
|environment|`number`|Environment information.|
|confidence|`number`|Confidence of the status information. The value ranges from 0 to 100. A larger value indicates more reliable result authenticity.|

#### LocationUpdateResultValue

An object that contains location update result.

|Field|Type|Description|
|---|---|---|
|value|`LocationUpdateResultContainer`|An object that contains location update results.|

#### MockLocation

An object that contains mock location settings.

|Field|Type|Description|
|---|---|---|
|mLatitude|`number`|Latitude value of location.|
|mLongitude|`number`|Longitude value of location.|

#### LocationUpdateRequest

An object that contains location update settings.

|Field|Type|Description|
|---|---|---|
|locationRequest|`LocationRequest`|Location settings request|
|uuid|`string`|Uuid|

#### LocationUpdateResultContainer

An object that contains location update result.

|Field|Type|Description|
|---|---|---|
|locationResult|`LocationUpdateResult`|An object that contains location update results.|

#### LocationUpdateResult

An object that contains location update result.

|Field|Type|Description|
|---|---|---|
|locations|`LocationResult[]`|An object that contains location update results.|


### Constants

#### PriorityConstants
|Field|Value|Description|
|---|---|---|
|PRIORITY_HIGH_ACCURACY|100|Used to request the most accurate location.|
|PRIORITY_BALANCED_POWER_ACCURACY|102|Used to request the block-level location.|
|PRIORITY_LOW_POWER|104|Used to request the city-level location.|
|PRIORITY_NO_POWER|105|Used to request the location with the optimal accuracy without additional power consumption.|
|PRIORITY_HD_ACCURACY|200|Used to request the high-precision location information. Currently, this parameter is available only for the requestLocationUpdatesEx method.|

#### NavigationRequestConstants
|Field|Value|Description|
|---|---|---|
|OVERPASS|1|Used to request the device navigation status.|
|IS_SUPPORT_EX|2|Used to check whether the device supports high-precision location.|

## 4. Configuration and Description

### Configuring Obfuscation Scripts

#### React Native

In order to prevent error while release build, you may need to add following lines in **`proguard-rules.pro`** file.

```text
-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
-repackageclasses
```

#### Cordova

Before building the APK, configure the obfuscation configuration file to prevent the HMS Core SDK from being obfuscated.

**NOTE**: This step is required only if you want to minify and obfuscate your app. By default obfuscation is disabled in Cordova and Ionic apps.

The obfuscation is done by **`ProGuard`.** By default, in Cordova and Ionic apps ProGuard is disabled. Even though ProGuard is not available, ProGuard support can be added through 3rd party ProGuard plugins. If ProGuard is enabled in your project, the Huawei Cordova Location plugin's ProGuard rules need to be added to your project. These rules are as follows:

```text
-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keep class com.huawei.hianalytics.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
-repackageclasses
```

---

## 5. Questions or Issues

If you have questions about how to use HMS samples, try the following options:

- [Stack Overflow](https://stackoverflow.com/questions/tagged/huawei-mobile-services) is the best place for any programming questions. Be sure to tag your question with **huawei-mobile-services**.
- [Huawei Developer Forum](https://forums.developer.huawei.com/forumPortal/en/home?fid=0101187876626530001) HMS Core Module is great for general questions, or seeking recommendations and opinions.
- [Huawei Developer Docs](https://developer.huawei.com/consumer/en/doc/overview/HMS-Core-Plugin) is place to official documentation for all HMS Core Kits, you can find detailed documentations in there.

---

## 6. Licensing and Terms

Huawei JS SDK is licensed under [Apache 2.0 license](LICENCE).

