一、获取 api 权限
1、uni.getLocation
通过下面的配置,我们就可以通过使用uni.authorize、uni.openSetting等来向用户获取使用uni.getLocation的权限
微信小程序文档: 授权
1 2 3 4 5 6 7 8 9 10 11
| { "mp-weixin": { "requiredPrivateInfos": ["getLocation"], "permission": { "scope.userLocation": { "desc": "你的位置信息将用于显示你当前位置的实时信息展示" } } } }
|
2、编写工具函数
通过上面的配置,现在我们可以编写一个真正的工具函数来获取位置信息了:
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
| const getLocationInfo = (coordType: string) => { return new Promise((resolve, reject) => { uni.getLocation({ type: coordType, success(res) { resolve(res) }, fail: (err) => { console.log('获取定位失败', err) uni.showToast({ title: '获取地址失败,将导致部分功能不可用', icon: 'none' }) } }) }) }
const openConfirm = (coordType: string) => { return new Promise((resolve, reject) => { uni.showModal({ title: '请求授权当前位置', content: '需要获取您的地理位置,请确认授权', success: async (res) => { if (res.confirm) { uni.openSetting({ success: async () => { const res = await getLocationInfo(coordType) resolve(res) } }) } else if (res.cancel) { uni.showToast({ title: '你拒绝了授权,将导致部分功能不可用', icon: 'none', duration: 1000 }) } } }) }) }
export const getGoeAuthorizeInfo = (coordType: string) => { return new Promise((resolve, reject) => { uni.authorize({ scope: 'scope.userLocation', success: async () => { const res = await getLocationInfo(coordType) resolve(res) }, fail: async () => { const res = await openConfirm(coordType) resolve(res) } }) }) }
|
二、获取位置信息
1、获取位置信息分析
完成上面操作后,我们可能知道了:
- 当前是否可以正常调用 uni.getLocation
- 用户是否开启了手机定位功能等
但我们并不能获取当前位置。原因如下:
通过阅读官方文档,针对不同的平台我们可以采用不同的方案:
2、app 中获取定位信息
步骤 1:获取 appKey
具体查看:https://ask.dcloud.net.cn/article/29
步骤 2:配置 manifest.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| { "app-plus": { "distribute": { "sdkConfigs": { "maps": { "baidu": { "appkey_ios": "xgYR5WpdskhIrO3QerFxS9gnshrBjG3t", "appkey_android": "xgYR5WpdskhIrO3QerFxS9gnshrBjG3t" } } } } } }
|
步骤 3:调用工具函数
此时调用工具函数就不会报错了
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
| import { ref } from 'vue' import { getGoeAuthorizeInfo } from '@/utils/locationAuthorization'
const coordType = 'wgs84'
const coordStr = ref('')
let currentLocal = ref('')
const getInitLocation = async () => { const { latitude, longitude }: any = await getGoeAuthorizeInfo(coordType) coordStr.value = `${latitude},${longitude}` const geoDate = { location: `${latitude},${longitude}`, type: coordType }
const { data: res } = await getGeoLocationApi(geoDate)
currentLocal.value = JSON.parse(res.data).result.formatted_address } getInitLocation()
|
3、小程序中后期定位信息