鸿蒙如何实现手机定位功能?具体操作如下:

鸿蒙如何实现手机定位功能?

开发者可以调用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);
}
}

 

文章来源:部分内容综合自网络,由“鸿蒙开发者老王”梳理成文。因觉优质,特此分享。