鸿蒙位置服务

位置服务

1、首先申请权限
在module.json5文件下申请位置权限

 "requestPermissions": [
 {
        "name": "ohos.permission.LOCATION",	// 权限名称,为系统已定义的权限
        "reason": "$string:location_reason",	// 申请权限的原因,当申请权限为user_grant权限时该字段为必填
        "usedScene": {	// 用于描述权限使用场景,当申请权限为user_grant权限时该字段为必填
          "abilities": [
            "EntryAbility"
          ],
          "when": "always"	// 调用时机(inuse:使用时;always:始终)
        }
      },
      {
        "name": "ohos.permission.APPROXIMATELY_LOCATION",
        "reason": "$string:location_reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "always"
        }
      }
    ]

$string:location_reason
会爆红,就需要在
在这里插入图片描述
文件下定义一下,
2、导入需要的包

import { abilityAccessCtrl, common, Permissions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { geoLocationManager } from '@kit.LocationKit';

3、看一下用户是否授权,没有授权拉起弹窗让用户授权

const permissions: Array<Permissions> = ['ohos.permission.LOCATION'];
// 使用UIExtensionAbility:将common.UIAbilityContext 替换为common.UIExtensionContext
export function reqPermissionsFromUser(permissions: Array<Permissions>, context: common.UIAbilityContext): void {
  let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
  // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
  atManager.requestPermissionsFromUser(context, permissions).then((data) => {
    let grantStatus: Array<number> = data.authResults;
    let length: number = grantStatus.length;
    for (let i = 0; i < length; i++) {
      if (grantStatus[i] === 0) {
        // 用户授权,可以继续访问目标操作
      } else {
        // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限
        return;
      }
    }
    // 授权成功
  }).catch((err: BusinessError) => {
    console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
  })
}

4、把这个方法加到页面启动的时候就查

aboutToAppear(){
// 使用UIExtensionAbility:将common.UIAbilityContext 替换为common.UIExtensionContext
    const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
    reqPermissionsFromUser(permissions, context);
}

5、开始获取当前位置

/*获取当前位置*/
let request: geoLocationManager.SingleLocationRequest = {
  'locatingPriority': geoLocationManager.LocatingPriority.PRIORITY_LOCATING_SPEED,//位置的优先级
  'locatingTimeoutMs': 10000//给的延迟,如果超了就显示获取位置失败
}
try {
  geoLocationManager.getCurrentLocation(request).then((result) => { // 调用getCurrentLocation获取当前设备位置,通过promise接收上报的位置
    result['locale'] = 'zh'
    console.log('current location: ' + JSON.stringify(result));
  })
    .catch((error:BusinessError) => { // 接收上报的错误码
      console.error('promise, getCurrentLocation: error=' + JSON.stringify(error));
    });
} catch (err) {
  console.error("errCode:" + JSON.stringify(err));
}

6、在添加一个页面就ok了
全部代码

import { abilityAccessCtrl, common, Permissions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { geoLocationManager } from '@kit.LocationKit';

const permissions: Array<Permissions> = ['ohos.permission.LOCATION'];
// 使用UIExtensionAbility:将common.UIAbilityContext 替换为common.UIExtensionContext
export function reqPermissionsFromUser(permissions: Array<Permissions>, context: common.UIAbilityContext): void {
  let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
  // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
  atManager.requestPermissionsFromUser(context, permissions).then((data) => {
    let grantStatus: Array<number> = data.authResults;
    let length: number = grantStatus.length;
    for (let i = 0; i < length; i++) {
      if (grantStatus[i] === 0) {
        // 用户授权,可以继续访问目标操作
      } else {
        // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限
        return;
      }
    }
    // 授权成功
  }).catch((err: BusinessError) => {
    console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
  })
}
//持续获取位置
// let request: geoLocationManager.ContinuousLocationRequest= {
//   'interval': 1,
//   'locationScenario': geoLocationManager.UserActivityScenario.NAVIGATION
// }
// let storedLocation: geoLocationManager.Location | null = null;
//
// let locationCallback = (location:geoLocationManager.Location):void => {
//   // 将传入的 location 存储在外部变量中
//   storedLocation = location;
//   // 输出存储的 location 数据
//   console.log('locationCallback: data: ' + JSON.stringify(storedLocation));
// };
//
// try {
//   geoLocationManager.on('locationChange', request, locationCallback);
// } catch (err) {
//   console.error("errCode:" + JSON.stringify(err));
// // }
/*获取当前位置*/
let request: geoLocationManager.SingleLocationRequest = {
  'locatingPriority': geoLocationManager.LocatingPriority.PRIORITY_LOCATING_SPEED,//位置的优先级
  'locatingTimeoutMs': 10000//给的延迟,如果超了就显示获取位置失败
}
try {
  geoLocationManager.getCurrentLocation(request).then((result) => { // 调用getCurrentLocation获取当前设备位置,通过promise接收上报的位置
    result['locale'] = 'zh'
    console.log('current location: ' + JSON.stringify(result));
  })
    .catch((error:BusinessError) => { // 接收上报的错误码
      console.error('promise, getCurrentLocation: error=' + JSON.stringify(error));
    });
} catch (err) {
  console.error("errCode:" + JSON.stringify(err));
}

@Entry
@Component
struct shouQuan {
  aboutToAppear() {
    // 使用UIExtensionAbility:将common.UIAbilityContext 替换为common.UIExtensionContext
    const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
    reqPermissionsFromUser(permissions, context);
    // geoLocationManager.getCurrentLocation(request).then((result) => { // 调用getCurrentLocation获取当前设备位置,通过promise接收上报的位置
    //   this.message=JSON.stringify(result)
    //   console.log('current location: ' + JSON.stringify(result));
    // })
  }


    @State location: string = '';
    @State message: string =''

    build() {
      Column() {
        Button('获取位置信息')
          .onClick( () => {
            // this.message=JSON.stringify(locationCallback)
            // this.location=JSON.stringify(request.)
          });

        Text('当前位置:')
          .fontSize(20)
          .padding(10);

        Text(this.message)
          .fontSize(16)
          .padding(10);

        Text()
          .fontSize(16)
          .padding(10);
      }
    }

}

你可能感兴趣的:(harmonyos,华为)