微信小程序获取地理位置 (异步openSetting)

微信小程序打开设置,不可以写在异步方法中,但是可以通过confirm中的success的回掉中。通过封装,同样可以实现异步操作

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
import authority from '@/utils/authority'
import setting from '@/utils/setting'

const defaultAddress = {
region_code: '320500',
latitude: 31.28339,
longitude: 120.60413
}

// 获取定位前价检查定位
async function beforeGetLocation() {
const authSetting = await setting.get()
if (authSetting['scope.userLocation'] !== false) {
return true
}
return new Promise(resolve => {
wx.showModal({
title: '定位失败',
content: '请打开位置授权',
success(res) {
if (res.confirm) {
setting.open('userLocation', isSuccess => {
if (isSuccess) {
resolve(true)
} else {
resolve(false)
}
})
} else {
resolve(false)
}
}
})
})
}

// 错误处理
export function getLocationError() {
authority.set(defaultAddress)
return defaultAddress
}

// 获取地理位置
export async function getLocation() {
const hasAUth = await beforeGetLocation()
if (!hasAUth) {
return getLocationError()
}
return new Promise(resolve => {
wx.getLocation({
type: 'wgs84',
success(res) {
wx.request({
url: 'https://apis.map.qq.com/ws/geocoder/v1/', // 腾讯地图api
data: {
location: `${res.latitude},${res.longitude}`,
key: ''
},
success({ data: { status, result } }) {
if (status) {
console.error('定位失败')
return getLocationError()
}
const {
ad_info: { city, adcode }
} = result
res.region_code = Math.floor(adcode / 100) * 100

const { region_code, latitude, longitude } = res
const user = region_code
? { region_code, latitude, longitude, city }
: defaultAddress
authority.set(user)
resolve(res)
},
fail(e) {
console.error(e)
resolve(getLocationError())
}
})
},
fail(e) {
console.error(e)
resolve(getLocationError())
}
})
})
}

export default {
get: getLocation
}