HarmoyOS Next 實現高德定位SDK
注:作者采用版本為 HarmonyOS 5.0.0 Release SDK和DevEco Studio 5.0.0 Release。
1.獲取本地AppID:
- 在index.pages的abountToAppear( ) 方法中獲取appID、并打印在Log日志,即可在程序運行時獲取本地項目的AppID。
2. 申請高德定位SDK的key:
- 高德地圖API
- 輸入本地的AppID即可申請獲取到高德定位SDK的Key
3. 配置權限聲明:在項目的module.json5
配置相關權限,以及配置相關權限reason。
- 其中 reason 可以在string.json中自行命名。
"requestPermissions": [{"name": "ohos.permission.APPROXIMATELY_LOCATION","reason": "$string:Harmony_location_permission_reason","usedScene": {"abilities": ["Harmony_location_demoAbility"],"when": "always"}},{"name": "ohos.permission.LOCATION","reason": "$string:Harmony_location_permission_reason","usedScene": {"abilities": ["Harmony_location_demoAbility"],"when": "always"}},{"name": "ohos.permission.LOCATION_IN_BACKGROUND","reason": "$string:Harmony_location_permission_reason","usedScene": {"abilities": ["Harmony_location_demoAbility"],"when": "always"}},{"name": "ohos.permission.INTERNET","reason": "$string:Harmony_location_permission_reason","usedScene": {"abilities": ["Harmony_location_demoAbility"],"when": "always"}},{"name": "ohos.permission.KEEP_BACKGROUND_RUNNING","reason": "$string:Harmony_location_permission_reason","usedScene": {"abilities": ["Harmony_location_demoAbility"],"when": "always"}}]
4. oh-package.json5 中獲取相關定位包:
"dependencies": {"@amap/amap_lbs_common": ">=1.2.0","@amap/amap_lbs_location": ">=1.2.0"}
5. 初始化隱私政策,創建AMapLocationManagerImpl,以及動態生成權限。
- 導入所需模塊
import { AMapLocation, AMapLocationManagerImpl } from '@amap/amap_lbs_location';
import { AMapPrivacyAgreeStatus, AMapPrivacyInfoStatus, AMapPrivacyShowStatus } from '@amap/amap_lbs_common';
import { Permissions } from '@ohos.abilityAccessCtrl';
import common from '@ohos.app.ability.common';
import abilityAccessCtrl, { PermissionRequestResult } from '@ohos.abilityAccessCtrl';
import { BusinessError } from '@ohos.base';
import { AMapLocationOption, AMapLocationReGeocodeLanguage, AMapLocationType, IAMapLocationListener } from '@amap/amap_lbs_location';
import geoLocationManager from '@ohos.geoLocationManager';
import { promptAction } from '@kit.ArkUI';
- 初始化隱私政策,創建AMapLocationManagerImpl及動態申請權限
locationManger?: AMapLocationManagerImpl;private context = getContext(this);onPageShow() {//設置KeyAMapLocationManagerImpl.setApiKey("**高德定位SDK的key**");//初始化隱私政策AMapLocationManagerImpl.updatePrivacyShow(AMapPrivacyShowStatus.DidShow, AMapPrivacyInfoStatus.DidContain, getContext(this))AMapLocationManagerImpl.updatePrivacyAgree(AMapPrivacyAgreeStatus.DidAgree, getContext(this))//創建AMapLocationManagerImplthis.locationManger = new AMapLocationManagerImpl(this.context);// 檢查系統定位是否開啟checkLocationEnabled();//獲取權限this.reqPermissionsFromUser(['ohos.permission.APPROXIMATELY_LOCATION','ohos.permission.LOCATION',]);}// 請求權限reqPermissionsFromUser(permissions: Array<Permissions>): void {let context: Context = getContext(this) as common.UIAbilityContext;let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();// requestPermissionsFromUser會判斷權限的授權狀態來決定是否喚起彈窗atManager.requestPermissionsFromUser(context, permissions).then((data: PermissionRequestResult) => {let grantStatus: Array<number> = data.authResults;let length: number = grantStatus.length;for (let i = 0; i < length; i++) {if (grantStatus[i] === 0) {// 用戶授權,可以繼續訪問目標操作this.message = '權限已授權';} else {// 用戶拒絕授權,提示用戶必須授權才能訪問當前頁面的功能,并引導用戶到系統設置中打開相應的權限this.message = '需要定位權限,請前往設置開啟';// 彈出 Toast 提示promptAction.showToast({message: '需要定位權限,請前往設置開啟',duration: 3000});return;}}// 授權成功}).catch((err: BusinessError) => {console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);})}
- 在struct 界面結構體外配置異步方法,用于檢查定位是否啟用。
// 檢查定位是否啟用
async function checkLocationEnabled() {try {let isEnabled = await geoLocationManager.isLocationEnabled();console.info("Location is enabled: " + isEnabled);} catch (error) {console.error("Failed to check location status: " + JSON.stringify(error));}
}
6. 開啟單次定位參數配置(也可自行配置為連續定位)
// 定位配置項options: AMapLocationOption = {priority: geoLocationManager.LocationRequestPriority.FIRST_FIX, //定位優先配置選項scenario: geoLocationManager.LocationRequestScenario.UNSET, //定位場景設置timeInterval: 2, //定位時間間隔distanceInterval: 0, //位置報告距離間隔maxAccuracy: 20, //定位精度 單位:米allowsBackgroundLocationUpdates: false, //是否允許后臺定位locatingWithReGeocode: true, //定位是否返回逆地理信息reGeocodeLanguage: AMapLocationReGeocodeLanguage.Chinese, //逆地址語言類型isOffset: true //是否加偏}
- 補充目前高德定位SDK的逆地理信息未適配HarmonyOS Next,可采用高德Web服務,進行經緯度逆向轉換為具體的地理信息。
- 定位信息監聽配置及經緯度信息解析:
// 定位監聽器listener: IAMapLocationListener = {onLocationChanged: (location) => {this.response = "\n"+ " 經度:" + location.longitude + "\n"+ " 緯度:" + location.latitude + "\n"+ " 海拔:" + location.altitude + "\n"+ " 精度:" + location.accuracy + "\n"+ " 速度:" + location.speed + "\n"+ " UTC時間:" + location.timeStamp + "\n"+ " 方向:" + location.direction + "\n"+ " 自啟動以來時間:" + location.timeSinceBoot + "\n"+ " 附加信息:" + location.additions + "\n"+ " 附加信息size:" + location.additionSize + "\n"+ " 逆地理:" + location.reGeo?.country}, onLocationError: (error) => {this.response = JSON.stringify(error);// todo something}};
7. 定位功能調用及關閉
@State response: string = '';---Row(){Button('開始定位').fontSize(20).margin(20).onClick(() => {this.locationManger?.setLocationListener(AMapLocationType.Updating, this.listener) //設置定位信息監聽this.locationManger?.setLocationOption(AMapLocationType.Updating, this.options) //設置定位配置項this.locationManger?.startUpdatingLocation() //開啟連續定位// this.locationManger?.stopUpdatingLocation() //關閉連續定位})Button('停止定位').fontSize(20).margin(20).onClick(() => {this.locationManger?.stopUpdatingLocation() //關閉連續定位})}Text("具體地址信息:" + this.response).fontSize(20)
8.具體效果如圖:
9. 使用時不要忘記右鍵下拉,開啟手機的定位服務。
10.錯誤碼說明:
- 總結:
以上為如何在HarmonyOS Next 5.0 使用高德定位SDK的模塊;
如有任何問題,請大家指出,本人再進行完善