第一步:配置 manifest.json(声明权限)

微信小程序强制要求在 manifest.json显式声明位置权限用途,否则无法调用定位 API。

✅ 操作步骤:

  1. 打开项目根目录下的 manifest.json 文件;
  2. 切换至 「源码视图」(非可视化编辑);
  3. 在 "mp-weixin" 对象内添加如下配置:
"mp-weixin": {
  "permission": {
    "scope.userLocation": {
      "desc": "您的位置将用于为您推荐最近的场馆"
    }
  },
  "requiredPrivateInfos": ["getLocation"]
}

💡 说明:

  • "desc" 字段为用户授权弹窗中显示的文案,需真实、简洁、符合场景;
  • "requiredPrivateInfos" 是微信 2023 年起新增的隐私接口白名单字段,缺一不可!
  • 修改完 manifest.json 后,建议在 HBuilderX 里停止运行,然后重新编译运行到微信开发者工具。因为 manifest.json 的改动有时不会触发热更新。

第二步:微信公众平台后台配置《用户隐私保护指引》

⚠️ 此步为硬性要求!未配置将导致 uni.getLocation 直接进入 fail 回调,且无明确错误提示

✅ 操作路径:

  1. 登录 微信公众平台 → 进入对应小程序;
  2. 左侧菜单:「账号设置」→「基本设置」→「服务内容声明」→「用户隐私保护指引」→「去完善」

第三步:代码实现(TypeScript 封装版)

1.模板部分(<template>

<template>
  <view class="p-4 bg-white">
    <button 
      class="bg-blue-500 text-white py-3 px-6 rounded-lg shadow"
      @tap="getUserLocation"
    >
      🔍 自动识别当前位置
    </button>

    <view v-if="latitude && longitude" class="mt-6 p-4 bg-gray-50 rounded-lg">
      <text class="block text-gray-700 font-medium">📍 当前坐标:</text>
      <text class="block mt-1 text-sm text-gray-600">
        经度:{{ longitude.toFixed(6) }} | 纬度:{{ latitude.toFixed(6) }}
      </text>
    </view>
  </view>
</template>

2.页面逻辑(<script setup lang="ts">

<script setup lang="ts">
import { ref } from 'vue';

const latitude = ref<number>(0);
const longitude = ref<number>(0);

/**
 * 获取用户当前位置(支持高精度 & GCJ-02 坐标系)
 */
const getUserLocation = () => {
  uni.getLocation({
    type: 'gcj02', // ✅ 国测局坐标,适用于腾讯/高德地图渲染
    isHighAccuracy: true, // ✅ 启用高精度定位(需设备支持)
    success: (res: UniApp.GetLocationSuccess) => {
      console.log('📍 定位成功:', res);
      latitude.value = res.latitude;
      longitude.value = res.longitude;

      uni.showToast({
        title: '定位成功',
        icon: 'success',
        duration: 1500
      });
    },
    fail: (err) => {
      console.warn('❌ 定位失败:', err);
      handleLocationError(err);
    }
  });
};

/**
 * 统一错误处理:区分授权拒绝 / 网络异常 / 设备限制等场景
 */
const handleLocationError = (err: any) => {
  if (err.errMsg?.includes('auth deny')) {
    // 用户已拒绝授权 → 引导手动开启
    uni.showModal({
      title: '位置权限未开启',
      content: '需要获取您的位置信息,才能为您匹配最近场馆。请前往设置开启。',
      confirmText: '去设置',
      success: (res) => {
        if (res.confirm) {
          uni.openSetting(); // 打开小程序系统设置页
        }
      }
    });
  } else if (err.errMsg?.includes('system error')) {
    uni.showToast({
      title: '系统定位服务异常',
      icon: 'none'
    });
  } else {
    uni.showToast({
      title: '定位失败,请检查网络或开启GPS',
      icon: 'none'
    });
  }
};
</script>

⚠️ 缺少任一环节均会导致 uni.getLocation 调用失败!

频率限制:不要在 onShow 里无脑调用。建议在用户进入首页或点击切换场馆时由用户触发。

uni.getLocation 只能给你数字(经纬度)。如果你想知道用户是在“上海市静安区XX路”,你需要使用地图服务商的 SDK。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐