#跟着若城学鸿蒙# web篇-获取定位

前言

在业务中,某些网页上需要获取用户的地理位置,然后按照用户搜索的兴趣点与用户的距离远近进行排序,这就需要h5能够获取到用户的位置。

由于 web 组件基于Chromium M114 版本开发,前端就可以使用navigator.geolocation.getCurrentPosition来获取位置信息。

实现

定位权限

首先需要在配置文件中声明定位权限

在模块中module.json5文件中配置一下权限

javascript 复制代码
      {
        "name" : "ohos.permission.APPROXIMATELY_LOCATION",
        "reason": "$string:user_grant_approximately_location_reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "inuse"
        }
      },
      {
        "name" : "ohos.permission.LOCATION",
        "reason": "$string:user_grant_approximately_location_reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "inuse"
        }
      },
      {
        "name" : "ohos.permission.LOCATION_IN_BACKGROUND",
        "reason": "$string:user_grant_approximately_location_reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "inuse"
        }
      }

这里我们配置了大致定位、精确定位和后台定位

前端页面

html 复制代码
<!DOCTYPE html>
<html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>位置信息</title>
</head>

<body>
<p id="locationInfo">位置信息</p>
<button onclick="getLocation()">获取位置</button>

<script>


    function getLocation() {
        console.error("获取位置");
        if (navigator.geolocation) {
            console.error("可以使用 ");

            const options = {
                enableHighAccuracy: true,  // 是否启用高精度模式
                timeout: 5000,           // 超时时间(毫秒)
                maximumAge: 0            // 缓存位置的最大年龄(毫秒)
            };

            navigator.geolocation.getCurrentPosition(
                (position) => {
                    console.error("获取到定位结果");
                    console.error("Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude);
                    // 在这里处理获取到的位置信息
                    var locationInfo = document.getElementById("locationInfo");
                    locationInfo.innerHTML = "Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude;
                },
                (error) => {
                    console.error("获取位置失败:",error);
                    // 在这里处理错误情况
                },
                options
            );
        } else {
            console.error("不可以使用");
        }
    }

</script>

web 组件

在 web 组件中,我们需要先允许访问位置信息,然后在收到前端请求时,进行处理

typescript 复制代码
          //定位
          .geolocationAccess(true)
          .onGeolocationShow((event)=>{
            AlertDialog.show({
              title: '位置权限请求',
              message: '是否允许获取位置信息',
              primaryButton: {
                value: '拒绝',
                action: () => {
                  if (event) {
                    event.geolocation.invoke(event.origin, false, false); // 不允许此站点地理位置权限请求
                  }
                }
              },
              secondaryButton: {
                value: '允许',
                action: () => {
                  if (event) {
                    let context = getContext(this) as common.UIAbilityContext;
                    let atManager = abilityAccessCtrl.createAtManager();
                    atManager.requestPermissionsFromUser(context, ["ohos.permission.APPROXIMATELY_LOCATION","ohos.permission.LOCATION"]).then((data) => {
                      event.geolocation.invoke(event.origin, true, false); // 允许此站点地理位置权限请求
                    }).catch((error: BusinessError) => {
                      console.error(`Failed to request permissions from user. Code is ${error.code}, message is ${error.message}`);
                    })
                  }
                }
              },
              cancel: () => {
                if (event) {
                  event.geolocation.invoke(event.origin, false, false); // 不允许此站点地理位置权限请求
                }
              }
            })

          })

当点击页面中的获取位置 时,会回调 web 的onGeolocationShow,这时候按照规范,需要先弹窗向用户解释为什么需要这个权限。当用户点击允许时,我们再去申请权限权限。当用户允许权限后,调用event.geolocation.invoke(event.origin, true, false); 通知前端可以定位了。当用户拒绝时回调event.geolocation.invoke(event.origin, false, false);通知前端没有权限。

这样我们就完成了定位请求。下面放一下效果图

相关推荐
SZYSK5 小时前
鸿蒙人脸识别算法放在终端里:和外挂授权 SDK 差在排障路径
物联网·算法·华为·harmonyos
贾伟康5 小时前
【健康菜谱助手|06】HarmonyOS ArkTS 烹饪计时器实战:处理倒计时、暂停、恢复和到期反馈
软件测试·移动开发·harmonyos·arkts·arkui
贾伟康8 小时前
【健康菜谱助手|05】HarmonyOS ArkTS 购物清单实战:去重食材并同步勾选、数量与清空动作
软件测试·移动开发·harmonyos·arkts·arkui
特立独行的猫a10 小时前
仓颉语言cj-tauri 跨端开发框架实战:给鸿蒙侧加一个「读设备电量」的原生能力
ui·harmonyos·tauri·1024程序员节·仓颉·鸿蒙pc
贾伟康19 小时前
【健康菜谱助手|01】HarmonyOS ArkTS 菜谱详情页实战:组织食材、营养、步骤和收藏状态
软件测试·移动开发·harmonyos·arkts·arkui
一目Leizi1 天前
折叠屏适配踩坑实录:从“一展开就变形“到一套代码适配多种形态【鸿蒙心迹】
华为·harmonyos
马剑威(威哥爱编程)1 天前
【HarmonyOS 7 小艺智能体实战】03:第一次建智能体——在小艺开放平台把骨架立起来
人工智能·华为·harmonyos
KevinChaos1 天前
HarmonyOS 7.0 端侧3DGS实验⑤:空洞、漂浮伪影与视角稳定
harmonyos
fellow991 天前
DSH Desktop - HarmonyOS Edition
harmonyos·openharmony·deepseek·deepseekharness