#我的鸿蒙开发手记# HarmonyOS Next元服务定位功能实现 原创 精华

小黄要努力
发布于 2025-5-8 18:10
浏览
0收藏

一、定位功能需求

元服务的定位功能能够准确获取用户当前所在位置的经纬度信息,基于获取到的用户位置,提供周边特定类型信息的查询功能。在应用界面中,以简洁直观的方式展示用户当前所在位置的地址信息(例如街道名称、所在区域等)。

二、授权访问设备位置信息

在使用位置服务系统能力前,需要检查是否已经获取用户授权访问设备位置信息。如未获得授权,可以向用户申请需要的位置权限。需要在module.json5中的requestPermissions设置以下配置:

  "requestPermissions": [
      {
        "name": "ohos.permission.LOCATION",
        "reason": "$string:app_name",
        "usedScene": {
          "abilities": [
            "Entry"
          ],
          "when":"inuse"
        }
      },
      {
        "name": "ohos.permission.APPROXIMATELY_LOCATION",
        "reason":"$string:app_name",
        "usedScene": {
          "abilities": [
            "Entry"
          ]
        }
      },

]

其中:

ohos.permission.LOCATION:用于获取精准位置,精准度在米级别。

ohos.permission.APPROXIMATELY_LOCATION:用于获取模糊位置,精确度为5公里。

访问设备的位置信息,必须申请权限,并且获得用户授权。

如果应用在后台运行时也需要访问设备位置,需要申请ohos.permission.LOCATION_IN_BACKGROUND权限,本文不做演示。​

三、获取经纬度

使用@ohos.geoLocationManager通过位置服务获取当前设备的经纬度。

let requestInfo:geoLocationManager.CurrentLocationRequest = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET,'maxAccuracy': 0};
try {
  geoLocationManager.getCurrentLocation(requestInfo).then((result) => {
    console.info('current location: ' + JSON.stringify(result));
  })
    .catch((error:BusinessError) => {
      console.error('promise, getCurrentLocation: error=' + JSON.stringify(error));
    });
} catch (err) {
  console.error("errCode:" + err.code + ", message:"  + err.message);
}

四、逆地理编码

由于元服务不支持使用@ohos.geoLocationManager中的geoLocationManager.getAddressesFromLocation将坐标转换为地理描述。需要使用地图服务(Map Kit)中的site(地点搜索)模块进行逆地理编码。

示例代码:

import { site } from ​​'@kit.MapKit';​​
let params: site.ReverseGeocodeParams = {
  location: {
latitude: 31.984410259206815,
longitude: 118.76625379397866
},
language: "zh",  //语言设置为中文
radius: 100
};
const reverse_result = await site.reverseGeocode(params);
console.info("Succeeded in reversing geocode.");

五、完整代码

import { geoLocationManager } from '@kit.LocationKit';
import { site } from '@kit.MapKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct LocationPage {
  @State Location:string = '点此进行定位'
  build() {
    RelativeContainer() {
      //定位
      Row(){
        Image($rawfile('LocateIconWhite.png'))//添加定位图标
          .width(30)
          .height(25)
            // 保持宽高比进行缩小或者放大,使得图片完全显示在显示边界内。
          .objectFit(ImageFit.Contain)

        Button(this.Location)//定位按钮
          .fontSize(30)
          .fontColor(Color.White)
          .backgroundColor('#00000000')
          .onClick(()=>{

            let requestInfo:geoLocationManager.CurrentLocationRequest = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET,'maxAccuracy': 0};
            try {
              geoLocationManager.getCurrentLocation(requestInfo).then(async (result) => {
                console.info('current location: ' + JSON.stringify(result));
                let params: site.ReverseGeocodeParams = {
                  location: {
                    latitude: result.latitude,
                    longitude: result.longitude
                  },
                  language: "zh",//语言设置为中文
                    radius: 100//搜索半径
                };
                const reverse_result = await site.reverseGeocode(params);
                this.Location= reverse_result.addressComponent.adminLevel1! + reverse_result.addressComponent.adminLevel2 + reverse_result.addressComponent.adminLevel3 //精确到区
                console.info("Succeeded in reversing geocode." +reverse_result.addressComponent.adminLevel1+reverse_result.addressComponent.adminLevel2+reverse_result.addressComponent.adminLevel3);
              })
                .catch((error:BusinessError) => {
                  console.error('promise, getCurrentLocation: error=' + JSON.stringify(error));
                });
            } catch (err) {
              console.error("errCode:" + err.code + ", message:"  + err.message);
            }
          })

      }
      .width('100%')
      .justifyContent(FlexAlign.Center)
      .alignRules({
        center: { anchor: '__container__', align: VerticalAlign.Center },
        middle: { anchor: '__container__', align: HorizontalAlign.Center }
      })
    }
    .height('100%')
    .width('100%')
    .backgroundColor(Color.Black)
  }
}

六、运行效果

#我的鸿蒙开发手记# HarmonyOS Next元服务定位功能实现-鸿蒙开发者社区


#我的鸿蒙开发手记# HarmonyOS Next元服务定位功能实现-鸿蒙开发者社区

通过上面的代码,展示了在鸿蒙应用中实现定位功能的完整步骤,从权限申请到获取经纬度坐标,再到将坐标转换为实际地址信息,相信你已经掌握位置服务的实现方法啦,快去试试吧!

#我的鸿蒙开发手记# HarmonyOS Next元服务定位功能实现-鸿蒙开发者社区


©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
分类
1
收藏
回复
举报
回复
    相关推荐