location-change.js 1.9 KB
Newer Older
L
lixu 已提交
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
const { invokeCallbackHandler: invoke } = UniServiceJSBridge
const callbackIds = []
const callbackOnErrorIds = []
const callbackOffErrorIds = []
let watchId

/**
 * 开始更新定位
 */
export function startLocationUpdate () {
  if (navigator.geolocation) {
    watchId = navigator.geolocation.watchPosition(
      res => {
        callbackIds.forEach(callbackId => {
          invoke(callbackId, res.coords)
        })
      },
      error => {
        callbackOnErrorIds.forEach(callbackId => {
          invoke(callbackId, {
            errMsg: 'getLocation:fail' + error.message
          })
        })
      }
    )
  } else {
    callbackOnErrorIds.forEach(callbackId => {
      invoke(callbackId, {
        errMsg: 'getLocation:fail device nonsupport geolocation'
      })
    })
  }
}

/**
 * 暂停更新定位
 * @param {*} callbackId
 */
export function stopLocationUpdate (callbackId) {
  if (watchId) {
    navigator.geolocation.clearWatch(watchId)
  } else {
    invoke(callbackId, { errMsg: 'stopLocationUpdate:fail' })
  }
  return {}
}

/**
 * 监听更新定位
 * @param {*} callbackId
 */
export function onLocationChange (callbackId) {
  callbackIds.push(callbackId)
}

/**
 * 监听更新定位失败
 * @param {*} callbackId
 */
export function onLocationChangeError (callbackId) {
  callbackOnErrorIds.push(callbackId)
}

// 移除实时地理位置变化事件的监听函数
export function offLocationChange (callbackId) {
  if (callbackId) {
    const index = callbackIds.indexOf(callbackId)
    if (index >= 0) {
      callbackIds.splice(index, 1)
    } else {
      callbackOffErrorIds.forEach(callbackId => {
        invoke(callbackId, {
          errMsg: 'offLocationChange:fail'
        })
      })
    }
  } else {
    callbackIds.length = 0
  }
}

// 移除实时地理位置变化事件的监听函数
export function offLocationChangeError (callbackId) {
  callbackOffErrorIds.push(callbackId)
}