
HarmonyOS开发-关于定位功能实现
开发者可以调用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);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
}
