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

发布: 2018-12-06 18:04:03标签: 前端开发

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

01import authority from '@/utils/authority'
02import setting from '@/utils/setting'
03
04const defaultAddress = {
05 region_code: '320500',
06 latitude: 31.28339,
07 longitude: 120.60413
08}
09
10// 获取定位前价检查定位
11async function beforeGetLocation() {
12 const authSetting = await setting.get()
13 if (authSetting['scope.userLocation'] !== false) {
14 return true
15 }
16 return new Promise(resolve => {
17 wx.showModal({
18 title: '定位失败',
19 content: '请打开位置授权',
20 success(res) {
21 if (res.confirm) {
22 setting.open('userLocation', isSuccess => {
23 if (isSuccess) {
24 resolve(true)
25 } else {
26 resolve(false)
27 }
28 })
29 } else {
30 resolve(false)
31 }
32 }
33 })
34 })
35}
36
37// 错误处理
38export function getLocationError() {
39 authority.set(defaultAddress)
40 return defaultAddress
41}
42
43// 获取地理位置
44export async function getLocation() {
45 const hasAUth = await beforeGetLocation()
46 if (!hasAUth) {
47 return getLocationError()
48 }
49 return new Promise(resolve => {
50 wx.getLocation({
51 type: 'wgs84',
52 success(res) {
53 wx.request({
54 url: 'https://apis.map.qq.com/ws/geocoder/v1/', // 腾讯地图api
55 data: {
56 location: `${res.latitude},${res.longitude}`,
57 key: ''
58 },
59 success({ data: { status, result } }) {
60 if (status) {
61 console.error('定位失败')
62 return getLocationError()
63 }
64 const {
65 ad_info: { city, adcode }
66 } = result
67 res.region_code = Math.floor(adcode / 100) * 100
68
69 const { region_code, latitude, longitude } = res
70 const user = region_code
71 ? { region_code, latitude, longitude, city }
72 : defaultAddress
73 authority.set(user)
74 resolve(res)
75 },
76 fail(e) {
77 console.error(e)
78 resolve(getLocationError())
79 }
80 })
81 },
82 fail(e) {
83 console.error(e)
84 resolve(getLocationError())
85 }
86 })
87 })
88}
89
90export default {
91 get: getLocation
92}
93
复制代码