鸿蒙中一键获取当前位置

我们在做功能的时候经常会遇到获取位置的功能那么今天小编和大家详细聊一下

那么这个功能这么做呢? 话不多说 先上官方链接  文档中心  点击直达

1,我们先来获取位置图标

// 获取详细地址位置
 

LocationButton({
  icon: LocationIconStyle.LINES, //  图标
  // text: LocationDescription.CURRENT_LOCATION, // 按钮
  // buttonType: ButtonType.Normal // 背景位置按钮样式
})

这三个属性我们看看官方文档是怎么说的吧

2,当我们按钮显示出来的时候 我们在给按钮注册点击事件

.onClick((event: ClickEvent, result: LocationButtonOnClickResult) => {
  if (result === LocationButtonOnClickResult.SUCCESS) {
    // 免去权限申请和权限请求等环节,获得临时授权,获取位置信息授权
    this.getCurrentLocationInfo() // 这里封装了一个方法 直接调用就行
  } else {
    promptAction.showToast({ message: '获取位置信息失败!' })
  }
})

下面是封装的方法

// 获取当前位置信息
getCurrentLocationInfo() {
  const requestInfo: geoLocationManager.LocationRequest = {
    'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
    'scenario': geoLocationManager.LocationRequestScenario.UNSET,
    'timeInterval': 1,
    'distanceInterval': 0,
    'maxAccuracy': 0
  };
  try {
    geoLocationManager.getCurrentLocation(requestInfo)
      .then((location: geoLocationManager.Location) => {
        // promptAction.showToast({ message: JSON.stringify(location) });
        // 把经纬度替换成我们真实的度数location.latitude, "longitude": location.longitude
        let reverseGeocodeRequest: geoLocationManager.ReverseGeoCodeRequest =
          // "latitude": location.latitude,  替换成自己当前的地理位置-经度
          // "longitude": location.longitude, 替换成自己当前的地理位置-维度
          // "maxItems": 1
          { "latitude": location.latitude, "longitude": location.longitude, "maxItems": 1 };
        geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest).then((data) => {
           // this.addForm.address 是我自己的后台数据 大家可以替换成自己的接口数据
          this.addForm.address = data[0].placeName as string 这里 this.addForm.address
          // console.log('getAddressesFromLocation: ' + JSON.stringify(data)); 打印的经度
          // promptAction.showToast({ message: JSON.stringify(data) });
        })
      })
      .catch((error: BusinessError) => {
        console.error('promise, getAddressesFromLocation: error=' + JSON.stringify(error));
      });
  } catch (err) {
    console.error("errCode:" + JSON.stringify(err));
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值