Integration of Huawei Site kit in Navigation Glove IoT application Using Kotlin - Part 3
Tags: android, kotlin, hms, huawei
Published: 2022-03-31 04:46:17

## Introduction

In this series of article, we can learn about **Navigation Glove application** and also we can learn about integration of the **Huawei Site kit** in Navigation Glove IoT application.

If you are new to this series of articles, follow my previous articles.

[Beginner: Integration of Huawei Account kit in Navigation Glove IoT application Using Kotlin - Part 1](https://forums.developer.huawei.com/forumPortal/en/topic/0202805462085750190)

[Beginner: Integration of Huawei Map kit in Navigation Glove IoT application Using Kotlin - Part 2](https://forums.developer.huawei.com/forumPortal/en/topic/0202805594751950193?fid=0101187876626530001)

**What is Site kit? **

**Site Kit** is basically used for apps to provide the place related services. This kit provide to search the places with **keyword**, **find nearby place**, **place suggestion for user input**, **get place details using the unique id**.

**Features of Huawei Site Kit**

**Keyword search:** With this function, users can specify keywords, coordinate bounds, and other information to search for places such as **tourist attractions**, **enterprises**, and **schools**.
**Nearby Place Search:** Huawei Site kit feature helps to get the nearby places using the current location of the user. For the nearby search we can set the POI **(Point of Interest)** where results can be filtered based on POI. User can search nearby **Bakery**, **School**, **ATM** etc.
**Place Details:** Huawei Site kit feature helps to search for details about a place based on the unique ID (Site Id) of the place. **SiteId **can get from **keyword** or **nearby** or **Place Suggestion search**.
In Place details we can get the **location name**, **formatted address**, **location website**, **location postal code**, **location phone numbers**, and list of location images URL etc.

**Place Search Suggestion:** This Huawei Site kit feature helps us to return search suggestions during the user input.
**Site Search Activity:** It opens built in search screen and search place in the activity and get the selected details in the response with Site.
**Autocomplete:** This helps application to build autocomplete place search with this function, your app can return a list of nearby places based on the current location of a user.

## Prerequisite

AppGallery Account
Android Studio 3.X
SDK Platform 19 or later
Gradle 4.6 or later
HMS Core (APK) 4.0.0.300 or later
Huawei Phone EMUI 3.0 or later
Non-Huawei Phone Android 4.4 or later
Service integration on AppGallery.

1. We need to [register as a developer](https://developer.huawei.com/consumer/en/doc/10104) account in AppGallery Connect.

2. Create an app by referring to [Creating a Project](https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-get-started#createproject) and [Creating an App in the Project](https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-get-started#createapp).

3. Set the data storage location based on the current location.

4. Enabling Site Kit Service on AppGallery Connect.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/00g0ykifbatk9cyik6ra.png)
 

5. Generating a Signing Certificate Fingerprint.

6. Configuring the Signing Certificate Fingerprint.

7. Get your **agconnect-services.json** file to the app root directory.

**Client development**

1. Create android project in android studio IDE.
2. Add the maven URL inside the repositories of buildscript and allprojects respectively (project level build.gradle file).
```
maven { url 'https://developer.huawei.com/repo/' }
```
3. Add the classpath inside the dependency section of the project level build.gradle file.

```
classpath 'com.huawei.agconnect:agcp:1.5.2.300'
```
4. Add the plugin in the app-level build.gradle file.
```
apply plugin: 'com.huawei.agconnect'
```
5. Add the below library in the app-level build.gradle file dependencies section.
```
implementation 'com.huawei.hms:site:5.2.0.301'
```
6. Add all the below permission in the AndroidManifest.xml.
```
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- Allow the app to obtain the coarse longitude and latitude of a user through the Wi-Fi network or base station. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<!-- Allow the app to receive location information from satellites through the GPS chip. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
```
7. Sync the project.

In my previous article we have learnt the integration of map kit.

In this article we will how to search place using Huawei search Intent.

In the current use case, user has to select the following things:

Source Location
Destination Location
Direction Type(Walking/Driving/Cycling)
After selecting all, user has to click on the navigate button.

When user select **source location** we will **add the marker** on the Map. When user select any place from the autocomplete search box, it will return the Site. It will be origin for direction API.

Similar to that when user select, the **destination location** will add the **marker on the Map**. When user select any place from the autocomplete search box, it will return the Site. It will be Destination for directions API.

**Site Kit Code**

Now let us jump to code part.

Step 1: Create the search intent

```
private val searchIntent = SearchIntent()
```

Step 2: Add your API key

```
private val API_KEY: String = "ADD_YOUR_API_KEY"
```
Step 3: set API Key in onCreate()

```
//Site kit
val apiKey = URLEncoder.encode(
API_KEY,
"utf-8"
)
searchIntent.setApiKey(apiKey)

```
Step 4: When the user clicks on the source location. Call the selectSourceLocation()

```
//Select source location
start.setOnClickListener {
//You can try the below one for older method
//selectSourceLocation()
/*val intent = searchIntent.getIntent(this)
startActivityForResult(intent, SearchIntent.SEARCH_REQUEST_CODE)*/
selectSourceLocation()
}
```

Step 5: Start activity result.

```
private fun selectSourceLocation() {
val intent = searchIntent.getIntent(this)
sourceLocationLauncher.launch(intent)
}
```

Step 6: When the user select the place, add marker on the Map and create origin request.

```
private var sourceLocationLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            val data: Intent? = result.data
            if (data != null) {
                if (SearchIntent.isSuccess(result.resultCode)) {
                    val site: Site = searchIntent.getSiteFromIntent(data)
                    start.text = site.getName()
                    originReq = Origin(site.location.lat, site.location.lng)
                    //Toast.makeText(application, site.getName(), Toast.LENGTH_LONG).show()
                    val build = CameraPosition.Builder()
                        .target(LatLng(site.location.lat, site.location.lng)).zoom(16f).build()
                    val cameraUpdate = CameraUpdateFactory.newCameraPosition(build)
                    hMap!!.animateCamera(cameraUpdate)
                    //Setting max and min zoom
                    //hMap!!.setMaxZoomPreference(10f)
                    //hMap!!.setMinZoomPreference(1f)
                    // Marker can be add by HuaweiMap
                    mMarker = hMap!!.addMarker(
                        MarkerOptions().position(LatLng(site.location.lat, site.location.lng))
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_baseline_location_on_24))
                            .clusterable(true)
                    )
                    mMarker?.showInfoWindow()

                    // circle can be added to HuaweiMap
                    /*mCircle = hMap!!.addCircle(
                        CircleOptions().center(LatLng(28.7041, 77.1025)).radius(45000.0).fillColor(
                            Color.GREEN))
                    mCircle?.fillColor = Color.TRANSPARENT*/

                }
            } else {
                Toast.makeText(application, "Unable to find the data", Toast.LENGTH_LONG).show()
            }
        }
```

**Repeat Steps 4, 5, 6** for Destination Location.


  

```
//Select Destination Location
        destination.setOnClickListener {
            selectDestinationLocation()
        }

 private fun selectDestinationLocation() {
        val intent = searchIntent.getIntent(this)
        destinationLocationLauncher.launch(intent)
    }

    private var destinationLocationLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            val data: Intent? = result.data
            if (data != null) {
                if (SearchIntent.isSuccess(result.resultCode)) {
                    val site: Site = searchIntent.getSiteFromIntent(data)
                    destination.text = site.getName()
                    destinationReq = Destination(site.location.lat, site.location.lng)
                    val build = CameraPosition.Builder()
                        .target(LatLng(site.location.lat, site.location.lng)).zoom(16f).build()
                    val cameraUpdate = CameraUpdateFactory.newCameraPosition(build)
                    hMap!!.animateCamera(cameraUpdate)
                    mMarker = hMap!!.addMarker(
                        MarkerOptions().position(LatLng(site.location.lat, site.location.lng))
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_baseline_destination_location_on_24))
                            .clusterable(true)
                    )
                    mMarker?.showInfoWindow()

                }
            } else {
                Toast.makeText(application, "Unable to find the data", Toast.LENGTH_LONG).show()
            }
        }
```

By now user can select the Source location and Destination Location. And also we have added marker on the map. Even you can circle to map. I’ve commented code if you need add a circle, you can uncomment.

## Result
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p2psj35me3ow1lqv9si9.png)
 

## Tips and Tricks

1. Make sure you are already registered as a Huawei developer.

2. Set min SDK version to 21 or later, otherwise you will get **AndriodManifest** to merge issue.

3. Make sure you have added the **agconnect-services.json** file to the app folder.

4. Make sure you have added the SHA-256 fingerprint without fail.

5. Make sure all the dependencies are added properly.

6. If you want to location feature in the Map, make sure you have added location permission in **AndroidManifest.xml** file.

7. If you install app in android **version 6 or greater**, then make sure you handled run time permission.

8. Make sure you have **encoded** your API key with **URLEncode** UTF-8.

## Conclusion

In this article, we have learnt the **integration of the Huawei Site Kit** in Navigation Glove application using Android Studio and Kotlin. And also we have learnt the **features** available by the Site kit. We have learnt the selection of **source** and **destination** location.

In next article, we will learn about the direction API.

## Reference

Site Kit - [Official document](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-sdk-about-the-service-0000001076188604)

Site Kit - [Code lab](https://developer.huawei.com/consumer/en/codelabsPortal/carddetails/HMSSiteKit)

Site Kit - [Training Video](https://developer.huawei.com/consumer/en/training/course/video/101582996919057158?hwplayerLibPath=https://developer.huawei.com/consumer/en/training//assets/lib/third/hwplayerLibPath/)