HarmonyOS开发-关于定位功能实现

鸿蒙时代
发布于 2022-3-2 10:38
浏览
1收藏

开发者可以调用HarmonyOS位置相关接口,获取设备实时位置,或者最近的历史位置。
首先需要申请定位权限:
ohos.permission.LOCATION
ohos.permission.LOCATION_IN_BACKGROUND
访问设备的位置信息,必须申请ohos.permission.LOCATION权限,并且获得用户授权。
调用其接口获取定位信息,直接上代码:
public class LocatorService{
private static final HiLogLabel TAG = new HiLogLabel(HiLog.INFO,0x0,“蛟龙腾飞—定位”);
private static Locator locator;
private static GeoAddress address;
MyLocatorCallback locatorCallback = new MyLocatorCallback();
// 初始化值
public Location getLocator(Context context){
HiLog.info(TAG,“获取定位”);
// 去除上传申请的address的信息
address.clearLatitude();
address.clearLongitude();
locator = new Locator(context);
// 进行定位
RequestParam requestParam = new RequestParam(RequestParam.SCENE_DAILY_LIFE_SERVICE);
locator.requestOnce(requestParam, locatorCallback);
return null;
}

public class MyLocatorCallback implements LocatorCallback {
    @Override
    public void onLocationReport(Location location) {
        HiLog.info(TAG, "%{public}s","位置: " + location.getLatitude() + "-" + location.getAltitude());
        getLocation(location);
    }

    @Override
    public void onStatusChanged(int type) {
    }

    @Override
    public void onErrorReport(int type) {
        HiLog.info(TAG, "错误: "+type);
    }
}

// 逆地理编码转化
public void getLocation(Location location){
    GeoConvert geoConvert = new GeoConvert();
    try {
        List<GeoAddress> geoAddress= geoConvert.getAddressFromLocation(location.getLatitude(), location.getLongitude(), 1);

        HiLog.info(TAG,"地理位置"+geoAddress.get(0));

        address = geoAddress.get(0);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

// 获取上一次申请的结果
private Location getLastLacation(){
    return locator.getCachedLocation();
}

// 返回值
public GeoAddress getGeoAddress(){
    return address;
}

/*
 *  结束定位
 *  */
public void stopLocator(){
    locator.stopLocating(locatorCallback);
}

}

分类
标签
harmonyos开发-关于定位功能实现.docx 19.74K 56次下载
2
收藏 1
回复
举报
回复
    相关推荐