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

471 阅读1分钟

微信使用实时位置

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

image.png

位置选择

位置选择的整体逻辑为:

  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,
  }
}