自學(xué)HarmonyOS應(yīng)用開(kāi)發(fā)(53)- 獲取當(dāng)前位置

目前的地圖軟件只能表示固定位置的地圖,我們希望在畫(huà)面第一次啟動(dòng)時(shí)能夠顯示當(dāng)前所在位置的地圖。首先來(lái)看動(dòng)作效果視頻:
聲明定位權(quán)限
修改所在HAP的config.json文件,以便獲取定位權(quán)限:
"reqPermissions": [...{"name": "ohos.permission.LOCATION","reason": "$string:reason_location","usedScene": {"ability": ["com.myapplication.LocationAbility"],"when": "always"}},...
申請(qǐng)定位權(quán)限
我們通過(guò)以下兩個(gè)方法是申請(qǐng)定位權(quán)限的代碼:
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);}}
有了這兩個(gè)方法,我們只要在適當(dāng)?shù)奈恢谜{(diào)用register方法就可以了。
注冊(cè)定位響應(yīng)代碼
申請(qǐng)當(dāng)前位置是一個(gè)異步處理,需要準(zhǔn)備并注冊(cè)一個(gè)回調(diào)對(duì)象:
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 {public void onLocationReport(Location location) {HiLog.info(LABEL, "onLocationReport");TaskDispatcher uiTaskDispatcher = owner_slice.getUITaskDispatcher();Revocable revocable = uiTaskDispatcher.asyncDispatch(new Runnable() {public void run() {tileMap.setLocation(location.getLongitude(), location.getLatitude());}});}public void onStatusChanged(int type) {}public void onErrorReport(int type) {}}
在registerLocationEvent方法用來(lái)注冊(cè)一個(gè)單次定位事件請(qǐng)求;在定位事件響應(yīng)對(duì)象中我們將獲得的位置信息通知給地圖對(duì)象。
參考代碼
獲取設(shè)備的位置信息:
https://developer.harmonyos.com/cn/docs/documentation/doc-guides/device-location-info-0000000000031900
完整代碼可以從以下鏈接下載:
https://github.com/xueweiguo/Harmony/tree/master/StopWatch
參考資料
Slippy map tilenames(包含各種轉(zhuǎn)換示例代碼):
https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames\
作者著作介紹
《實(shí)戰(zhàn)Python設(shè)計(jì)模式》是作者去年3月份出版的技術(shù)書(shū)籍,該書(shū)利用Python 的標(biāo)準(zhǔn)GUI 工具包tkinter,通過(guò)可執(zhí)行的示例對(duì)23 個(gè)設(shè)計(jì)模式逐個(gè)進(jìn)行說(shuō)明。這樣一方面可以使讀者了解真實(shí)的軟件開(kāi)發(fā)工作中每個(gè)設(shè)計(jì)模式的運(yùn)用場(chǎng)景和想要解決的問(wèn)題;另一方面通過(guò)對(duì)這些問(wèn)題的解決過(guò)程進(jìn)行說(shuō)明,讓讀者明白在編寫(xiě)代碼時(shí)如何判斷使用設(shè)計(jì)模式的利弊,并合理運(yùn)用設(shè)計(jì)模式。

對(duì)設(shè)計(jì)模式感興趣而且希望隨學(xué)隨用的讀者通過(guò)本書(shū)可以快速跨越從理解到運(yùn)用的門(mén)檻;希望學(xué)習(xí)Python GUI 編程的讀者可以將本書(shū)中的示例作為設(shè)計(jì)和開(kāi)發(fā)的參考;使用Python 語(yǔ)言進(jìn)行圖像分析、數(shù)據(jù)處理工作的讀者可以直接以本書(shū)中的示例為基礎(chǔ),迅速構(gòu)建自己的系統(tǒng)架構(gòu)。
覺(jué)得本文有幫助?請(qǐng)分享給更多人。
關(guān)注微信公眾號(hào)【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_(kāi)發(fā),面向?qū)ο笏伎迹?/span>
