鸿蒙开发之地理位置

发布时间:2024年01月02日

一、权限申请

获取位置信息需要先在module.json5中申请权限,而权限的申请在API9版本发生了变动如下

//API9之前只申请这个就可以米级定位
{'name':  'ohos.permission.LOCATION'},//API9之前申请的权限

//API9后两个权限同时申请才可以获取米级定位,只下边一个权限只能精准到5公里
{'name':  'ohos.permission.APPROXIMATELY_LOCATION'},//API9及之后需要增加申请的权限

所以,如果是高精度的位置信息需要两个权限都申请,如果只是需要模糊定位为了节能只需要第二个权限就够了。

二、检测用户权限

1、检测用户权限需要先获取Token,token是异步回调的
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
 async accessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
    let atManager = abilityAccessCtrl.createAtManager()
    let grantStatus: abilityAccessCtrl.GrantStatus

    let tokenID: number
    try {
      let bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
      tokenID = bundleInfo.appInfo.accessTokenId
    } catch (err) {
      console.log('location 获取地理位置token失败')
    }

    try {
     grantStatus = await atManager.checkAccessToken(tokenID,permission)
    } catch (err) {
      console.log('获取地理位置token检测失败')
    }

    return grantStatus
  }
2、获取token后,开始查询用户权限状态
async checkPermission() {

    let permissions: Array<Permissions> = ['ohos.permission.LOCATION','ohos.permission.APPROXIMATELY_LOCATION']
    let locationStatus = await this.accessToken(permissions[0])
    let roximateyStatus = await this.accessToken(permissions[1])
    if (locationStatus == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED &&
    roximateyStatus == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
      console.log('location 已经申请完权限了')
    } else {
      console.log('location 需要申请权限')
      this.requestPermission()
    }
  }

三、申请权限

//申请权限
requestPermission() {
    let atManager = abilityAccessCtrl.createAtManager()
    let permissions: Array<Permissions> = ['ohos.permission.LOCATION','ohos.permission.APPROXIMATELY_LOCATION']
    atManager.requestPermissionsFromUser(getContext(this),permissions,(err,permissionResult) => {
      if (err) {
        console.log('申请权限失败')
        return
      }

      let grantStatus: Array<number> = permissionResult.authResults
      let grantPermissions: Array<string> = permissionResult.permissions
      let length: number = grantStatus.length
      console.log('location user permissioned length' + JSON.stringify(grantPermissions)+length)
      for(let i = 0; i<length; i++) {
        if (grantStatus[i] === 0) {
          console.log('location user has agreed permissioned')
        } else {//用户不同意,就跳转APP的设置页面方便用户设置权限
          console.log('location user has disagree permissioned')
          this.openPermissionSettings()
        }
      }
    })
  }

  /*
 * 跳转到权限设置页面
 * */
  openPermissionSettings() {
  let context = getContext(this) as common.UIAbilityContext
  let  wantInfo = {
    action: 'action.settings.app.info',
    parameters: {
      settingsParamBundleName: 'com.example.myapplication'
    }
  }
  context.startAbility(wantInfo).then(() => {
    console.log('location open setting page')
  }).catch((err) => {
    console.log('location open setting page failed')
  })
}

四、权限完成后,开启定位

startLocate() {

    this.checkPermission().then(() => {
      let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
      let locationChange = (location) => {
        console.log('location change:data = '+JSON.stringify(location))
      }
      try {
        //监听位置变化
        geoLocationManager.on('locationChange',requestInfo,locationChange)
      } catch (err) {
        console.error("location change errCode:" + err.code + ",errMessage:" + err.message)
      }

      try {
        //获取当前的地理位置(坐标等)
        geoLocationManager.getCurrentLocation((err,location) => {
          if (err) {
            console.log('location getCurrentLocation err = '+JSON.stringify(err))
          }
          if (location) {
            console.log('location getCurrentLocation = '+JSON.stringify(location))
              //{"latitude":40,"longitude":116,"altitude":43.5,"accuracy":5,"speed":0,"timeStamp":1704176491,"direction":45,"timeSinceBoot":13563917977759,"additions":"","additionSize":0,"isFromMock":false}
            let latitude = location.latitude
            let longitude = location.longitude
            let maxItems = 1
            let reverseGeocodeReq = {'latitude':latitude,'longitude':longitude,'maxItems':maxItems}
            //根据坐标转化为地理描述
            geoLocationManager.getAddressesFromLocation(reverseGeocodeReq,(err,val) => {
              if (err) {
                console.log('location getAddressesFromLocation err = '+JSON.stringify(err))
                //这里一直报错,怀疑是模拟器的问题。看错误code说可能网络问题需要重试,但是重试多次还是如下报错,如果可以还是用真机试试
                //{"code":3301300,"message":"BussinessError 3301300: Reverse geocoding query failed."}
              }
              if (val) {
                console.log('location getAddressesFromLocation = '+JSON.stringify(val))
              }
            })

            //获取国家码
            geoLocationManager.getCountryCode((err,val) => {
              if (err) {
                console.log('location getCountryCode err = '+JSON.stringify(err))
              }
              if (val) {
                console.log('location getCountryCode = '+JSON.stringify(val))
                //location getCountryCode = {"country":"CN","type":4}
              }
            })
          }
        })
      } catch (err) {
        console.log('location getCurrentLocation catch err = '+JSON.stringify(err))
      }

    }).catch(err => {
      console.error("location permission errCode:" + err.code + ",errMessage:" + err.message)

    })
  }

五、ets中全部代码

import geoLocationManager from '@ohos.geoLocationManager';
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import bundleManager from '@ohos.bundle.bundleManager';
import common from '@ohos.app.ability.common';

@Entry
@Component
struct OfficialLocationPage {
  @State message: string = '开始定位'

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(18)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            this.startLocate()
          })
      }
      .width('100%')
    }
    .height('100%')
  }

  async accessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
    let atManager = abilityAccessCtrl.createAtManager()
    let grantStatus: abilityAccessCtrl.GrantStatus

    let tokenID: number
    try {
      let bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
      tokenID = bundleInfo.appInfo.accessTokenId
    } catch (err) {
      console.log('location 获取地理位置token失败')
    }

    try {
     grantStatus = await atManager.checkAccessToken(tokenID,permission)
    } catch (err) {
      console.log('获取地理位置token检测失败')
    }

    return grantStatus
  }

  async checkPermission() {

    let permissions: Array<Permissions> = ['ohos.permission.LOCATION','ohos.permission.APPROXIMATELY_LOCATION']
    let locationStatus = await this.accessToken(permissions[0])
    let roximateyStatus = await this.accessToken(permissions[1])
    if (locationStatus == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED &&
    roximateyStatus == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
      console.log('location 已经申请完权限了')
    } else {
      console.log('location 需要申请权限')
      this.requestPermission()
    }
  }

  requestPermission() {
    let atManager = abilityAccessCtrl.createAtManager()
    let permissions: Array<Permissions> = ['ohos.permission.LOCATION','ohos.permission.APPROXIMATELY_LOCATION']
    atManager.requestPermissionsFromUser(getContext(this),permissions,(err,permissionResult) => {
      if (err) {
        console.log('申请权限失败')
        return
      }

      let grantStatus: Array<number> = permissionResult.authResults
      let grantPermissions: Array<string> = permissionResult.permissions
      let length: number = grantStatus.length
      console.log('location user permissioned length' + JSON.stringify(grantPermissions)+length)
      for(let i = 0; i<length; i++) {
        if (grantStatus[i] === 0) {
          console.log('location user has agreed permissioned')
        } else {
          console.log('location user has disagree permissioned')
          this.openPermissionSettings()
        }
      }
    })
  }

  /*
 * 跳转到权限设置页面
 * */
  openPermissionSettings() {
  let context = getContext(this) as common.UIAbilityContext
  let  wantInfo = {
    action: 'action.settings.app.info',
    parameters: {
      settingsParamBundleName: 'com.example.myapplication'
    }
  }
  context.startAbility(wantInfo).then(() => {
    console.log('location open setting page')
  }).catch((err) => {
    console.log('location open setting page failed')
  })
}
  startLocate() {

    this.checkPermission().then(() => {
      let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
      let locationChange = (location) => {
        console.log('location change:data = '+JSON.stringify(location))
      }
      try {
        geoLocationManager.on('locationChange',requestInfo,locationChange)
      } catch (err) {
        console.error("location change errCode:" + err.code + ",errMessage:" + err.message)
      }

      try {
        //获取当前的地理位置
        geoLocationManager.getCurrentLocation((err,location) => {
          if (err) {
            console.log('location getCurrentLocation err = '+JSON.stringify(err))
          }
          if (location) {
            console.log('location getCurrentLocation = '+JSON.stringify(location))
            //{"latitude":40,"longitude":116,"altitude":43.5,"accuracy":5,"speed":0,"timeStamp":1704176491,"direction":45,"timeSinceBoot":13563917977759,"additions":"","additionSize":0,"isFromMock":false}
            let latitude = location.latitude
            let longitude = location.longitude
            let maxItems = 1
            let reverseGeocodeReq = {'latitude':latitude,'longitude':longitude,'maxItems':maxItems}
            //根据坐标转化为地理描述
            geoLocationManager.getAddressesFromLocation(reverseGeocodeReq,(err,val) => {
              if (err) {
                console.log('location getAddressesFromLocation err = '+JSON.stringify(err))
                //{"code":3301300,"message":"BussinessError 3301300: Reverse geocoding query failed."}
              }
              if (val) {
                console.log('location getAddressesFromLocation = '+JSON.stringify(val))
              }
            })

            //获取国家码
            geoLocationManager.getCountryCode((err,val) => {
              if (err) {
                console.log('location getCountryCode err = '+JSON.stringify(err))
              }
              if (val) {
                console.log('location getCountryCode = '+JSON.stringify(val))
                //location getCountryCode = {"country":"CN","type":4}
              }
            })
          }
        })
      } catch (err) {
        console.log('location getCurrentLocation catch err = '+JSON.stringify(err))
      }

    }).catch(err => {
      console.error("location permission errCode:" + err.code + ",errMessage:" + err.message)

    })
  }
}

文章来源:https://blog.csdn.net/Lu_Ca/article/details/135340224
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。