9433cfb9创建于 2025年12月31日历史提交
/**
 * 步骤 1: 定义接口来描述成功和失败的回调数据结构
 */
// 描述成功回调的结果结构
type ILocationSuccessResult = {
  latitude: number;
  longitude: number;
  address: string | null; // 明确 address 不可能是 undefined
  // ... 你可以根据需要添加其他字段,如 speed, accuracy 等
}

// 描述失败回调的结果结构
type ILocationFailResult ={
  errCode: number;
  errMsg: string;
}


/**
 * @description 获取地理位置信息,并将 uni.getLocation Promise化
 * @param {any} options - uni.getLocation 的参数选项
 * @returns {Promise<ILocationSuccessResult>} 返回一个包含位置信息的 Promise
 */
// 步骤 2: 函数签名使用我们定义的接口
const getLocation = (options?: any): Promise<ILocationSuccessResult> => {
  const defaultOptions: any = {
    type: 'gcj02',
    geocode: true,
    isHighAccuracy: false,
  };

  const finalOptions: any = { ...defaultOptions, ...options };

  return new Promise((resolve, reject) => {
    uni.getLocation({
      ...finalOptions,
      success: (res) => {
        // 步骤 3: 在 resolve 时,使用类型断言,并指向我们定义的接口
        resolve(res as ILocationSuccessResult);
      },
      fail: (error) => {
        let errorMessage = '获取定位失败';
        // 步骤 4: 在处理错误时,也对 error 对象进行类型断言
        const err = error as ILocationFailResult;
        switch (err.errCode) {
          case 1505003:
            errorMessage = '系统定位未开启,请在系统设置中开启';
            break;
          case 1505004:
            errorMessage = '应用定位权限未开启,请在系统设置中授权';
            break;
          case 1505600:
            errorMessage = '定位超时,请检查网络或稍后重试';
            break;
          case 1505605:
            errorMessage = '腾讯定位API Key配置错误,请检查 manifest.json';
            break;
        }
        reject(new Error(`${errorMessage} (错误码: ${err.errCode})`));
      },
    });
  });
};

export { getLocation };