zhengyiming
2025-02-10 0470145fcd755d3f87bffc7a985bd3cc82c5f3f6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import Taro from '@tarojs/taro';
import axios from 'axios';
 
type LocationResponse = {
  result?: {
    ad_info?: {
      adcode?: number;
      city?: string;
      district?: string;
      nation?: string;
      nation_code?: number;
      province?: string;
    };
    ip?: string;
    location?: {
      lat?: number;
      lng?: number;
    };
  };
};
 
export class LocationUtils {
  static wxLocation: LocationResponse;
 
  static pendingPromise: Promise<LocationResponse>;
 
  static currentProvinceName: string;
 
  static blackList = ['江西省'];
 
  static async getLocation() {
    if (!this.wxLocation) {
      if (!this.pendingPromise) {
        this.pendingPromise = this.getLocationImp().finally(() => {
          this.pendingPromise = undefined;
        });
      }
      let res = await this.pendingPromise;
 
      this.currentProvinceName = res?.result?.ad_info?.province ?? '';
 
      this.wxLocation = res;
    }
    return this.wxLocation;
  }
 
  static async getLocationImp() {
    let geocoderRes = await this.getLocationByIp().catch(() => this.getLocationByIp());
    console.log('geocoderRes: ', geocoderRes);
 
    return geocoderRes;
  }
 
  static async getLocationByGeocoder() {
    let setting = await Taro.getSetting();
    if (!setting.authSetting['scope.userLocation']) {
      await Taro.authorize({
        scope: 'scope.userLocation',
      });
    }
    let res = await Taro.getLocation({
      type: 'gcj02',
    });
    return await this.geocoder({ latitude: res.latitude, longitude: res.longitude });
  }
 
  static async getBaseUrlByLocation() {
    try {
      let res = await this.getLocation();
      return this.blackList.includes(this.currentProvinceName)
        ? process.env.BASE_URL_JX
        : process.env.BASE_URL;
    } catch (error) {
      console.log('getLocation error: ', error);
      return process.env.BASE_URL;
    }
  }
 
  static geocoder({ latitude, longitude }: { latitude?: number; longitude?: number }) {
    return axios
      .get<LocationResponse>(
        `https://apis.map.qq.com/ws/geocoder/v1?location=${latitude},${longitude}&key=HH7BZ-5L2KI-TN3GW-U5HKU-MK5H3-VOBZH`
      )
      .then((res) => res.data);
  }
 
  static getLocationByIp() {
    return axios
      .get<LocationResponse>(
        `https://apis.map.qq.com/ws/location/v1/ip?key=HH7BZ-5L2KI-TN3GW-U5HKU-MK5H3-VOBZH`
      )
      .then((res) => res.data);
  }
 
  static isProvinceChange(provinceName: string) {
    return (
      provinceName !== this.currentProvinceName &&
      (this.blackList.includes(provinceName) || this.blackList.includes(this.currentProvinceName))
    );
  }
}