get-location.js 2.0 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2
import {
  wgs84togcj02,
Q
qiang 已提交
3 4
  gcj02towgs84,
  warpPlusErrorCallback
fxy060608's avatar
fxy060608 已提交
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
} from '../util'

import {
  invoke
} from '../../bridge'

function getLocationSuccess (type, position, callbackId) {
  const coords = position.coords
  if (type !== position.coordsType) {
    if (process.env.NODE_ENV !== 'production') {
      console.log(
        `UNIAPP[location]:before[${position.coordsType}][lng:${
          coords.longitude
        },lat:${coords.latitude}]`
      )
    }
    let coordArray
    if (type === 'wgs84') {
      coordArray = gcj02towgs84(coords.longitude, coords.latitude)
    } else if (type === 'gcj02') {
      coordArray = wgs84togcj02(coords.longitude, coords.latitude)
    }
    if (coordArray) {
      coords.longitude = coordArray[0]
      coords.latitude = coordArray[1]
      if (process.env.NODE_ENV !== 'production') {
        console.log(
          `UNIAPP[location]:after[${type}][lng:${coords.longitude},lat:${
            coords.latitude
          }]`
        )
      }
    }
  }

  invoke(callbackId, {
    type,
    altitude: coords.altitude || 0,
    latitude: coords.latitude,
    longitude: coords.longitude,
    speed: coords.speed,
    accuracy: coords.accuracy,
    address: position.address,
    errMsg: 'getLocation:ok'
  })
}

export function getLocation ({
  type = 'wgs84',
  geocode = false,
55
  altitude = false,
D
DCloud_LXH 已提交
56
  isHighAccuracy = false,
57
  highAccuracyExpireTime
fxy060608's avatar
fxy060608 已提交
58
} = {}, callbackId) {
Q
qiang 已提交
59
  const errorCallback = warpPlusErrorCallback(callbackId, 'getLocation')
fxy060608's avatar
fxy060608 已提交
60 61 62 63 64 65 66 67 68 69
  plus.geolocation.getCurrentPosition(
    position => {
      getLocationSuccess(type, position, callbackId)
    },
    e => {
      // 坐标地址解析失败
      if (e.code === 1501) {
        getLocationSuccess(type, e, callbackId)
        return
      }
Q
qiang 已提交
70
      errorCallback(e)
fxy060608's avatar
fxy060608 已提交
71 72
    }, {
      geocode: geocode,
73
      enableHighAccuracy: isHighAccuracy || altitude,
Q
qiang 已提交
74 75
      timeout: highAccuracyExpireTime,
      coordsType: type
fxy060608's avatar
fxy060608 已提交
76 77 78
    }
  )
}