使用uniapp开发微信小程序-位置选择

微信使用实时位置

如果需要使用用户的位置信息,首先需要在manifest.json中配置权限:

在这里插入图片描述

位置选择

位置选择的整体逻辑为:

  1. 如果没有弹出过授权弹窗,则弹窗提示:如果本次用户允许使用位置,则默认打开当前位置,否则使用微信默认位置。弹出后记录用户选择,下次打开时不再弹窗。
  2. 如果已经弹出过授权弹窗:用户允许使用位置,则默认打开用户当前位置,如果用户上一次拒绝使用位置,则使用微信默认位置。
import { useUserStore } from '@/store'

export function useLocation() {
  const userStore = useUserStore()
  function chooseLocation(latitude?: number, longitude?: number) {
    return new Promise((resolve) => {
      // 需要回写位置
      if (latitude && longitude) {
        openMap(latitude, longitude, resolve)
        return;
      }
      // 先获取用户授权状态
      uni
        .getSetting()
        .then((res) => {
          if (!res.authSetting['scope.userLocation'] && !userStore.authLocation) {
            // 1、如果没有授权定位,并且没有弹框过
            uni
              .authorize({
                scope: 'scope.userLocation',
              })
              .then(() => {
                // 1.1、用户允许使用位置
                openMap(null, null, resolve)
                userStore.setAuthLocation(true) // 授权成功,设置状态为
              })
              .catch(() => {
                // 1.2、用户拒绝使用位置,默认定位到北京市政府
                userStore.setAuthLocation(true) // 拒绝授权,设置状态为
                openMap(undefined, undefined, resolve)
              })
          } else if (res.authSetting['scope.userLocation']){
            // 2、已经授权,直接调用openMap方法,chooseLocation会自动定位到用户所在位置
            openMap(null, null, resolve)
          } else {
            // 3、未授权,并且已经弹框提示过,默认定位到北京市政府
            openMap(undefined, undefined, resolve)
          }
        })
        .catch((err) => {
          console.log('getSetting', err)
          // 4、获取授权状态失败,默认定位到北京市政府
          openMap(undefined, undefined, resolve)
        })
    })
  }
  function openMap(latitude: number = 39.904179, longitude: number = 116.407387, resolve: Function) {
    uni
      .chooseLocation({
        latitude: latitude,
        longitude: longitude,
      })
      .then((res) => {
        console.log('openMap', res)
        resolve && resolve(res)
      })
  }
  return {
    chooseLocation,
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值