| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- /** 用戶位置信息 */
- import {
- getUserRegion
- } from '@/api/system'
- // import store from '@/store'
- /** 用戶手机定位 */
- let mLocation = {
- lat: null,
- lng: null
- }
- /** 用户地址回调 */
- let callFunction = null
- export async function mGetPosition() {
- let getCurPages = getCurrentPages()
- let getRoute = getCurPages.length > 0 ? getCurPages[0].route : ''
- const client_hash = uni.getStorageSync('client_hash')
- if (mLocation.lat && mLocation.lng) {
- return mLocation
- }
- if (!client_hash && getRoute == 'pages/page/login/index') {
- return null
- }
- let getObj = await new Promise(resolve => {
- uni.getLocation({
- type: 'gcj02',
- success: res => resolve(res),
- fail: e => {
- console.log('获取位置失败!', e)
- }
- })
- })
- mLocation = getObj
- mLocation.lat = getObj.latitude
- mLocation.lng = getObj.longitude
- return mLocation
- }
- /** 腾讯地图定位 */
- // 初始化或更新用户位置信息缓存
- let positionType = null
- let retryNum = 1
- export function getPosition(callFn) {
- if (callFn) {
- callFunction = callFn
- }
- mGetPosition().then(res => {
- showPosition()
- })
- }
- function showPosition() {
- if (retryNum > 6) return false
- let userRegion = uni.getStorageSync('userRegion')
- let intervalTime = 30 * 60 * 1000 // 默认半小时过期
- // 判断是否已存在位置信息缓存
- if (userRegion) {
- userRegion = JSON.parse(userRegion)
- // 获取后台返回的有效时间间隔
- let timesTamp = new Date().getTime()
- if (userRegion.expire * 1000 > timesTamp) {
- intervalTime = userRegion.expire * 1000 - timesTamp
- retryNum = 1
- } else {
- intervalTime = 10000
- retryNum++
- }
- }
- if (mLocation.lat && mLocation.lng) {
- positionType = 'mobile'
- if (userRegion) {
- // 当前时间大于等于过期时间(超过有效时间间隔后)重新请求接口更新缓存
- if (callFunction) {
- callFunction(userRegion)
- }
- callFunction = null
- setTimeout(() => {
- fetchPosition(mLocation)
- }, intervalTime)
- } else {
- // 页面首次渲染请求接口设置缓存
- fetchPosition(mLocation)
- }
- }
- }
- // 根据用户经纬度请求用户位置信息
- function fetchPosition(position) {
- if (!position.lat && !position.lng) {
- console.error('获取经纬度失败!')
- return false
- }
- uni.setStorageSync('miscPosition', JSON.stringify(position))
- let params = {
- lng_lat_type: positionType,
- lat: position.lat,
- lng: position.lng
- }
- getUserRegion(params).then(res => {
- if (res.status === 'success') {
- // 设置或更新用户位置信息缓存
- if (callFunction) {
- callFunction(res.data)
- }
- callFunction = null
- uni.setStorageSync('userRegion', JSON.stringify(res.data))
- // 提交用户位置信息状态
- // store.commit('FETCH_USER_REGION', res.data)
- showPosition()
- }
- })
- }
- export default {
- mLocation,
- mGetPosition,
- getPosition
- }
|