uniapp获取当前定位信息
发布时间 2024-03-03 19:53:41

一、获取 api 权限

1、uni.getLocation

  通过下面的配置,我们就可以通过使用uni.authorizeuni.openSetting等来向用户获取使用uni.getLocation的权限

微信小程序文档: 授权

  • 配置 manifest.json
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) {
// console.log('获取定位信息',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
{
/* 5+App特有相关 */
"app-plus": {
// ...
/* 应用发布信息 */
"distribute": {
// ...
/* SDK配置 */
"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、小程序中后期定位信息

上一页
2024-06-11 00:39:23
下一页