getLocation.ts 5.5 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import { extend } from '@vue/shared'
Q
qiang 已提交
2 3 4 5 6 7 8
import {
  defineAsyncApi,
  API_GET_LOCATION,
  API_TYPE_GET_LOCATION,
  GetLocationProtocol,
  GetLocationOptions,
} from '@dcloudio/uni-api'
Q
qiang 已提交
9
import { MapType, getMapInfo } from '../../../helpers/location'
Q
qiang 已提交
10
import { getJSONP } from '../../../helpers/getJSONP'
11
import { request } from '../network/request'
12
import { loadMaps } from '../../../view/components/map/maps'
Q
qiang 已提交
13 14 15 16 17

type GeoRes = (coords: GeolocationCoordinates, skip?: boolean) => void

export const getLocation = <API_TYPE_GET_LOCATION>defineAsyncApi(
  API_GET_LOCATION,
D
DCloud_LXH 已提交
18 19 20 21
  (
    { type, altitude, highAccuracyExpireTime, isHighAccuracy },
    { resolve, reject }
  ) => {
Q
qiang 已提交
22
    const mapInfo = getMapInfo()
Q
qiang 已提交
23 24 25 26 27 28 29

    new Promise((resolve: GeoRes, reject) => {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (res) => resolve(res.coords),
          reject,
          {
D
DCloud_LXH 已提交
30
            enableHighAccuracy: isHighAccuracy || altitude,
31
            timeout: highAccuracyExpireTime || 1000 * 100,
Q
qiang 已提交
32 33 34 35 36 37
          }
        )
      } else {
        reject(new Error('device nonsupport geolocation'))
      }
    })
38
      .catch((error) => {
Q
qiang 已提交
39
        return new Promise((resolve: GeoRes, reject) => {
Q
qiang 已提交
40
          if (mapInfo.type === MapType.QQ) {
41
            getJSONP(
Q
qiang 已提交
42
              `https://apis.map.qq.com/ws/location/v1/ip?output=jsonp&key=${mapInfo.key}`,
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
              {
                callback: 'callback',
              },
              (res: any) => {
                if ('result' in res && res.result.location) {
                  const location = res.result.location
                  resolve(
                    {
                      latitude: location.lat,
                      longitude: location.lng,
                    } as GeolocationCoordinates,
                    true
                  )
                } else {
                  reject(new Error(res.message || JSON.stringify(res)))
                }
              },
              () => reject(new Error('network error'))
            )
Q
qiang 已提交
62
          } else if (mapInfo.type === MapType.GOOGLE) {
63 64
            request({
              method: 'POST',
Q
qiang 已提交
65
              url: `https://www.googleapis.com/geolocation/v1/geolocate?key=${mapInfo.key}`,
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
              success(res) {
                const data: AnyObject = res.data as AnyObject
                if ('location' in data) {
                  resolve({
                    latitude: data.location.lat,
                    longitude: data.location.lng,
                    accuracy: data.accuracy,
                  } as GeolocationCoordinates)
                } else {
                  reject(
                    new Error(
                      (data.error && data.error.message) || JSON.stringify(res)
                    )
                  )
                }
              },
              fail() {
                reject(new Error('network error'))
              },
            })
          } else {
            reject(error)
          }
Q
qiang 已提交
89 90 91
        })
      })
      .then((coords: GeolocationCoordinates, skip?: boolean) => {
92
        const wgs84Map = [MapType.GOOGLE]
93 94
        if (
          (type && type.toUpperCase() === 'WGS84') ||
95
          wgs84Map.includes(mapInfo.type) ||
96 97
          skip
        ) {
Q
qiang 已提交
98 99
          return coords
        }
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
        if (mapInfo.type === MapType.QQ) {
          return new Promise((resolve: GeoRes) => {
            getJSONP(
              `https://apis.map.qq.com/jsapi?qt=translate&type=1&points=${coords.longitude},${coords.latitude}&key=${mapInfo.key}&output=jsonp&pf=jsapi&ref=jsapi`,
              {
                callback: 'cb',
              },
              (res: any) => {
                if (
                  'detail' in res &&
                  'points' in res.detail &&
                  res.detail.points.length
                ) {
                  const location = res.detail.points[0]
                  resolve(
                    extend({}, coords, {
                      longitude: location.lng,
                      latitude: location.lat,
                    })
                  )
                } else {
                  resolve(coords)
                }
              },
              () => resolve(coords)
            )
          })
        }
        if (mapInfo.type === MapType.AMAP) {
          return new Promise((resolve: GeoRes) => {
            loadMaps([], () => {
              window.AMap.convertFrom(
                [coords.longitude, coords.latitude],
                'gps',
                (_: string, res: any) => {
                  if(res.info === 'ok' && res.locations.length){
                    const {lat,lng} = res.locations[0]
                    resolve(
                      extend({}, coords, {
                        longitude: lng,
                        latitude: lat,
                      })
                    )
                  }else{
                    resolve(coords)
                  }
                }
              )
            })
          })
        }
Q
qiang 已提交
151
      })
152
      .then((coords: GeolocationCoordinates|any) => {
153 154 155 156 157 158 159 160 161 162
        resolve({
          latitude: coords.latitude,
          longitude: coords.longitude,
          accuracy: coords.accuracy,
          speed: coords.altitude || 0,
          altitude: coords.altitude || 0,
          verticalAccuracy: coords.altitudeAccuracy || 0,
          // 无专门水平精度,使用位置精度替代
          horizontalAccuracy: coords.accuracy || 0,
        })
Q
qiang 已提交
163 164 165 166 167 168 169 170
      })
      .catch((error) => {
        reject(error.message)
      })
  },
  GetLocationProtocol,
  GetLocationOptions
)