[Huawei Developers] HMS Community:
View attachment 5611617

Introduction

In this article, I will be integrating Huawei Site Kit in a Weather Application. Site Kit offers you many search capabilities such as place search, time zone search, geocoding, and administrative region search, helping your app attract more users. REST API provides a set of HTTP/HTTPS APIs, with which you can initiate HTTP/HTTPS requests to call functions such as keyword search, nearby place search, place detail search, place search suggestion, autocomplete, geocoding, and time zone search. The Site SDK for Android is a set of APIs that can be called to develop place-related functions. You can use this SDK to easily add place search functions to your Android app, including keyword search, nearby place search, place detail search, and place search suggestion.

React Native

React Native helps you to create real and exciting mobile apps with the help of JavaScript only, which is supportable for both android and iOS platforms.

Just code once, and the React Native apps are available for both iOS and Android platforms which helps to save development time.

React Native is a framework that builds a hierarchy of UI components to build the JavaScript code.

It uses the same fundamental UI building blocks as regular iOS and Android apps.

Requirements

1. Any operating system (MacOS, Linux and Windows).

2. Must have a Huawei phone with HMS 4.0.2.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. Minimum API Level 21 is required.

5. Required EMUI 9.0.0 and later version devices.

Integrate HMS Dependencies

1. First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.

2. Create a project in android studio, refer Creating an Android Studio Project.

3. Generate a SHA-256 certificate fingerprint.

4. To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > SHA256 code.

Or use cmd as explained in SHA256 CODE

5. Create an App in AppGallery Connect.

6. Download the agconnect-services.json file from App information, copy and paste in android Project under app directory, as follows.

View attachment 5611619

7. Enter SHA-256 certificate fingerprint and click Save, as follows.

View attachment 5611621

React Native Project Preparation

8. Environment set up, refer below link.

Get Started with React Native · React Native

React Native allows developers who know React to create native apps. At the same time, native developers can use React Native to gain parity between native platforms by writing common features once.

reactnative.dev

9. Create project using below command.

react-native init project name

10. Download Plugin Using NPM.

Download React Native Site Plugin and place @hmscore/react-native-hms-site in the node_modules directory of your React Native project.

11. Open settings.gradle located under the project-dir > android directory and add

include ':react-native-hms-site'

project(':react-native-hms-site').projectDir = new File(rootProject.projectDir, '../@hmscore/node_modules/react-native-hms-site/android')

12. Go to buildscript > dependencies and add dependency configurations.

buildscript {

dependencies {

classpath 'com.huawei.agconnect:agcp:1.4.1.300'

}

}

13. Configure build dependencies.

dependencies {

implementation project(":react-native-hms-site")

}

14. Add following in the MainApplication file

import com.huawei.hms.rn.site.RNHMSSitePackage;

List<ReactPackage> getPackages() {

List<ReactPackage> packages = new PackageList(this).getPackages();

packages.add(new RNHMSSitePackage());

return packages;

Development

Before using the plugin methods, you need to initialize the search service. A Config object that contains apiKey must be passed to the initializeService method of the RNHMSSite module.

import RNHMSSite from '@hmscore/react-native-hms-site';

RNHMSSite.initializeService(config)

.then(() => {

console.log('Service is initialized successfully');

})

.catch((err) => {

console.log('Error : ' + err);

});

React Native Site Plugin provides the following core capabilities for you to quickly build apps with which your users can explore the world around them:

Place Search: Returns a place list based on keywords entered by the user.

Nearby Place Search: Searches for nearby places based on the current location of the user's device.

Place Details: Searches for details about a place.

Search Suggestion: Returns a list of place suggestions.

Autocomplete: Returns an autocomplete place and a list of suggested places based on the entered keyword.

SearchWidget: Creates a search widget, when a user enters a keyword in the search box, the widget displays a list of suggested places to the user.

Text Search

RNHMSSite.textSearch(searchreq) used to get the places list. It will return the list of places based on request.

const onTextSearch = () => {
let textSearchReq = {
query: "Delhi",
location: {
lat: 28.7041,
lng: 77.1025,
},
radius: 1000,
countryCode: 'IN',
language: 'en',
pageIndex: 1,
pageSize: 5,
hwPoiType: RNHMSSite.HwLocationType.XYZ,

//Replace XYZ with any place you would like to find
poiType: RNHMSSite.LocationType.ABC,
politicalView: "IN"
};
RNHMSSite.textSearch(textSearchReq)
.then((res) => {
Alert.alert("Text Search", JSON.stringify(res));
})
.catch((err) => {
Alert.alert("Text Search", JSON.stringify(err));
});
};

Detail Search

RNHMSSite.detailSearch(searchreq) is used to get the place details.

const onDetailSearch = () => {
let detailSearchReq = {
siteId: ' ', // the place id which can be obtain using getSiteid API.
language: 'en',
politicalView: 'in'
};
RNHMSSite.detailSearch(detailSearchReq)
.then((res) => {
Alert.alert("Detail Search", JSON.stringify(res));
})
.catch((err) => {
Alert.alert("Detail Search", JSON.stringify(err));
});
};

Near By Search

RNHMSSite.nearbySearch(searchreq) is used to get the nearby places details.

const onNearbySearch = () => {
let nearbySearchReq = {
query: 'Delhi',
location:
{
lat: 28.7041,
lng: 77.1025, },
radius: 1000,
poiType: RNHMSSite.LocationType.ADDRESS,
countryCode: 'IN',
language: 'en',
pageIndex: 1,
pageSize: 5,
hwPoiType: RNHMSSite.HwLocationType.XYZ,
politicalView: "in"
};
RNHMSSite.nearbySearch(nearbySearchReq)
.then((res) => {
alert(JSON.stringify(res));
console.log(JSON.stringify(res));
})
.catch((err) => {
alert(JSON.stringify(err));
console.log(JSON.stringify(err));
});
};

Query Suggestion

RNHMSSite.querySuggestion(searchreq) is used to get the details.

const onQuerySuggestion = () => {
let querySuggestionReq = {
query: 'Delhi',
location: {
lat: 28.7041,
lng: 77.1025,
},
radius: 1000,
countryCode: 'IN',
language: 'en',
poiTypes: [RNHMSSite.LocationType.ADDRESS, RNHMSSite.LocationType.GEOCODE],
};
RNHMSSite.querySuggestion(querySuggestionReq)
.then((res) => {
Alert.alert("Query Suggestion", JSON.stringify(res));
})
.catch((err) => {
Alert.alert("Query Suggestion", JSON.stringify(err));
});
};

Using Geocoding:

Obtains the longitude and latitude of a place based on its structured address.

Url: https://siteapi.cloud.huawei.com/mapApi/v1/siteService/geocode?key=API KEY

Note:

For details of API KEY, please refer to Obtaining the API Key.

Request API

Response

Call

To know more, refer to this document.

SearchBar.js

import React, { useState } from 'react'

import { View, TextInput, StyleSheet, Dimensions } from 'react-native';

import { EvilIcons } from '@expo/vector-icons';

//fetchWeatherData fetches the response from the API.

export default function SearchBar({ fetchWeatherData }) {

const [cityName, setCityName] = useState('');

return (

<View style={styles.searchBar}>

<TextInput

placeholder='Enter City name'

value={cityName}

onChangeText={(text) => setCityName(text)}

/>

<EvilIcons name="search" size={28} color="black" onPress={() => //Searches the query}/>

</View>

)

}

const styles = StyleSheet.create({

searchBar: {

marginTop: 35,

flexDirection: 'row',

alignItems: 'center',

justifyContent: 'space-between',

width: Dimensions.get('screen').width - 20,

borderWidth: 1.5,

paddingVertical: 10,

borderRadius: 25,

marginHorizontal: 10,

paddingHorizontal: 10,

backgroundColor: 'lightgray',

borderColor: 'lightgray'

}

})

Testing

Run the android App using the below command.

react-native run-android

Result

View attachment 5611623

Tips and Tricks

1. Set minSdkVersion to 19 or higher.

2. Add API key in project.

3. For project cleaning, navigate to android directory and run the below command.

gradlew clean

Conclusion

In this article, we have learnt that how to integrate site kit into the app using React Native. React Native Site Plugin provides adaptation code for HUAWEI Site Kit to use the React Native platform. With HUAWEI Site Kit, your app can provide users with convenient and secure access to diverse, place-related services. You can try and use various other APIs like OpenWeatherMap (Best for Weather Forecast), AccuWeather(Best for Weather Conditions, Images, Cyclones & More), Dark Sky(Best for Forecast & Historical Data), Tomorrow.io (formerly ClimaCell) (Best for Realtime, Short Term & Hourly Forecasts)

Reference

Site Kit: Documentation

Site Kit: Training Video