声明定位权限
修改所在HAP的config.json文件,以便获取定位权限:
"reqPermissions": [
...
{
"name": "ohos.permission.LOCATION",
"reason": "$string:reason_location",
"usedScene": {
"ability": [
"com.myapplication.LocationAbility"
],
"when": "always"
}
},
...
申请定位权限
我们通过以下两个方法是申请定位权限的代码:
private void register(Context ability) {
context = ability;
requestPermission(PERM_LOCATION);
}
private void requestPermission(String permission) {
if (context.verifySelfPermission(permission) != IBundleManager.PERMISSION_GRANTED) {
context.requestPermissionsFromUser(new String[] {permission}, 0);
}
}
有了这两个方法,我们只要在适当的位置调用register方法就可以了。
注册定位响应代码
申请当前位置是一个异步处理,需要准备并注册一个回调对象:
private void registerLocationEvent() {
if (hasPermissionGranted(PERM_LOCATION)) {
locator = new Locator(context);
requestParam = new RequestParam(RequestParam.SCENE_NAVIGATION);
locator.requestOnce(requestParam, locatorCallback);
}
}
private void unregisterLocationEvent() {
if (locator != null) {
locator.stopLocating(locatorCallback);
}
}
private boolean hasPermissionGranted(String permission) {
return context.verifySelfPermission(permission) == IBundleManager.PERMISSION_GRANTED;
}
private class MyLocatorCallback implements LocatorCallback {
@Override
public void onLocationReport(Location location) {
HiLog.info(LABEL, "onLocationReport");
TaskDispatcher uiTaskDispatcher = owner_slice.getUITaskDispatcher();
Revocable revocable = uiTaskDispatcher.asyncDispatch(new Runnable() {
@Override
public void run() {
tileMap.setLocation(location.getLongitude(), location.getLatitude());
}
});
}
@Override
public void onStatusChanged(int type) {
}
@Override
public void onErrorReport(int type) {
}
}
在registerLocationEvent方法用来注册一个单次定位事件请求;在定位事件响应对象中我们将获得的位置信息通知给地图对象。
参考代码
获取设备的位置信息:
https://developer.harmonyos.com/cn/docs/documentation/doc-guides/device-location-info-0000000000031900
完整代码可以从以下链接下载:
https://github.com/xueweiguo/Harmony/tree/master/StopWatch
参考资料
Slippy map tilenames(包含各种转换示例代码):
https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames\