OpenHarmony开源社区
直播中

nhcp

16年用户 1137经验值
私信 关注
[经验]

实现HarmonyOS定位功能的过程分享

一、api讲解

1、准备工作

集成权限,需要在config.json文件中添加定位权限,如下代码所示

"reqPermissions": [

{"name": "ohos.permission.LOCATION"}

],

在MainAbility界面进行动态申请权限,代码如下

String[] permissions = {

SystemPermission.LOCATION

    };

    requestPermissionsFromUser(permissions, 0);

2、实例化Locator对象

实例化定位对象,代码如下

Locator locator = new Locator(context);

3、实例化LocatorCallback对象

实例化LocatorCallback对象,用于向系统位置提供上报的途径,代码如下

/**

* 定位回调

 */

public class MyLocatorCallback implements LocatorCallback {

    /**

     * 定位成功的回调,用于开发者获取具体地理的经纬度详细信息

     * [url=home.php?mod=space&uid=3142012]@param[/url] location 定位成功返回的对象

     */

    @Override

    public void onLocationReport(Location location) {

    }

    /**

     *定位的时候,定位服务状态发生改变的时候,触发这个函数

     * @param type 服务状态码,有如下几个状态

     *             Locator.SESSION_START  表示定位请求已被系统接受。

     *            Locator.SESSION_STOP     指示位置请求已完成。

     */

    @Override

    public void onStatusChanged(int type) {

        HiLog.error(LABEL,"状态改变");

    }

    /**

     * 定位失败触发此函数

     * @param type 定位失败错误码,具体状态如下

     *     1.  Locator.ERROR_PERMISSION_NOT_GRANTED: 应用程序调用定位器接口时,尚未授予定位权限

     *      2.Locator.ERROR_SWITCH_UNOPEN :应用程序调用定位器接口时,位置服务已禁用(GPS 功能未打开)

     */

    @Override

    public void onErrorReport(int type) {

        HiLog.error(LABEL,"定位失败");

    }

}

4、实例化RequestParam对象,

向应用实例实例化对象的建议系统,提供用于请求参数类型上的参数列表的位置服务,以及参考位置报告的频率,开发)

RequestParam requestParam = new RequestParam(RequestParam.PRIORITY_ACCURACY, 0, 0);

5、开始定位

locator.startLocating(requestParam, locatorCallback);

6、停止定位

locator.stopLocating(locatorCallback);

7、(逆)地理编码

实例化GeoConvert对象,代码变成

//todo 实例化GeoConvert对象

GeoConvert geoConvert = new GeoConvert();

8、获取返回结果

调用getAddressFromLocation(double latitude, double longitude, int maxItems),坐标转换位置信息,代码如下

/**

* 获取地理位置

         * latitude:当前的经度

         *longitude:当前的维度

         * maxItems:指定返回的地址列表的最大长度。建议取值范围为1-5。如果指定的值小于1,则使用默认值1。

         */

        geoConvert.getAddressFromLocation(40.0, 116.0, 1);

二、代码实现

绘制xml界面

绘制基本代码的xml界面,一个文本组件用于定位和获取经纬度然后(逆)地理编码,获取特定的结果,显示一个文本组件,用于

<DirectionalLayout

xmlns:ohos="http://schemas.huawei.com/res/ohos"

ohos:height="match_parent"

ohos:width="match_parent"

ohos:alignment="top"

ohos:orientation="vertical">

<Text

    ohos:text_alignment="center"

    ohos:id="$+id:text_start_Location"

    ohos:height="80vp"

    ohos:width="match_parent"

    ohos:background_element="$graphic:background_ability_main"

    ohos:layout_alignment="horizontal_center"

    ohos:text="开始定位"

    ohos:text_size="20vp"

    />

<Text

    ohos:text_alignment="horizontal_center"

    ohos:id="$+id:text_result"

    ohos:height="match_parent"

    ohos:width="match_parent"

    ohos:background_element="#ed6262"

    ohos:layout_alignment="horizontal_center"

    ohos:multiple_lines="true"

    ohos:text="显示结果"

    ohos:text_size="20vp"

    />

java代码实现

package com.newdemo.myapplication.slice;

import com.newdemo.myapplication.ResourceTable;

import ohos.aafwk.ability.AbilitySlice;

import ohos.aafwk.content.Intent;

import ohos.agp.components.Component;

import ohos.agp.components.Text;

import ohos.hiviewdfx.HiLog;

import ohos.hiviewdfx.HiLogLabel;

import ohos.location.*;

import java.util.List;

public class MainAbilitySlice extends AbilitySlice {

private  Locator locator;

private GeoConvert geoConvert;

private Text Text_result;//todo 结果按钮

static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG");

@Override

public void onStart(Intent intent) {

    super.onStart(intent);

    super.setUIContent(ResourceTable.Layout_ability_main);

    //todo 查找显示结果按钮

    Text_result= (Text) findComponentById(ResourceTable.Id_text_result);

    //todo 实例化locator对象

    locator= new Locator(MainAbilitySlice.this);

    //todo  构造requestParam参数

    RequestParam requestParam = new RequestParam(RequestParam.PRIORITY_ACCURACY, 0, 0);

    MyLocatorCallback locatorCallback = new MyLocatorCallback();

    //todo 实例化geoConvert

    geoConvert       = new GeoConvert();

    /**

     * 实现按钮事件 开始定位

     */

    findComponentById(ResourceTable.Id_text_start_Location).setClickedListener(new Component.ClickedListener() {

        @Override

        public void onClick(Component component) {

            //为开启定位服务方法

            locator.requestOnce(requestParam, locatorCallback);

        }

    });

}

/**

 * 定位回调

 */

public class MyLocatorCallback implements LocatorCallback {

    /**

     * 定位成功的回调,用于开发者获取具体地理的经纬度详细信息

     * @param location 定位成功返回的对象

     */

    @Override

    public void onLocationReport(Location location) {

        try {

            StringBuilder stringBuilder=new StringBuilder();

            HiLog.error(LABEL, "定位成功" + "Latitude====>" + location.getLatitude() + "===Longitude====>" + location.getLongitude());

            stringBuilder.append("定位成功").append("n");

            //todo 根据经纬度获取详细信息

            List<GeoAddress> list = geoConvert.getAddressFromLocation(location.getLatitude(), location.getLongitude(), 1);

            if(list.size()>0){

                for (int i=0;i<list.size();i++){

                    stringBuilder.append( "Latitude====>" + list.get(i).getLatitude() ).append("n");

                    stringBuilder.append("Longitude====>" + list.get(i).getLongitude()).append("n");

                    stringBuilder.append("地理位置"+list.get(0).getDescriptions(0));

                    HiLog.error(LABEL, "地理位置" + list.get(0).toString());

                    //todo 显示结果

                    getUITaskDispatcher().syncDispatch(()   -> {

                        Text_result.setText(stringBuilder.toString());

                    });

                }

            }

            HiLog.error(LABEL, "geoConvert is over" );

        }catch (Exception e){

            HiLog.error(LABEL, "Exception" + e.toString());

        }

    }

    /**

     *定位的时候,定位服务状态发生改变的时候,触发这个函数

     * @param type 服务状态码,有如下几个状态

     *             Locator.SESSION_START  表示定位请求已被系统接受。

     *            Locator.SESSION_STOP     指示位置请求已完成。

     */

    @Override

    public void onStatusChanged(int type) {

        HiLog.error(LABEL,"状态改变");

    }

    /**

     * 定位失败触发此函数

     * @param type 定位失败错误码,具体状态如下

     *     1.  Locator.ERROR_PERMISSION_NOT_GRANTED: 应用程序调用定位器接口时,尚未授予定位权限

     *      2.Locator.ERROR_SWITCH_UNOPEN :应用程序调用定位器接口时,位置服务已禁用(GPS 功能未打开)

     */

    @Override

    public void onErrorReport(int type) {

        HiLog.error(LABEL,"定位失败");

    }

}

}

三、运行效果

原作者:Mayism

更多回帖

发帖
×
20
完善资料,
赚取积分