uniapp开发获取用户位置信息功能解析

问题描述

uniapp官网上没有找到关于获取用户手机定位是否打开的接口,而在开发小程序的时候,遇到了用户虽然授权了位置服务,但是还是获取不到用户位置,发现实际的问题是,用户的手机定位功能没开。

uniapp相关接口

1、uni.authorize 提前向用户发起授权请求。

uni.authorize接口地址
在这里插入图片描述

接口描述及demo演示

这个接口需要去理解接口的描述。不然可能会一直绕进去。
在这里插入图片描述
在页面onShow方法中添加下面的代码块。在页面show的时候。
在这里插入图片描述
注意观察下面的333333和444444的日志打印,可以看到,这个日志是在用户操作后,才打印出来的。
在这里插入图片描述

2、uni.getLocation 获取当前的地理位置、速度。

uni.getLocation接口地址
在这里插入图片描述

3、uni.openSetting 调起客户端小程序设置界面,返回用户设置的操作结果

在这里插入图片描述

解决方案

1、uniapp微信小程序端

uni.authorize({
				scope: 'scope.userLocation',
				success() {
					console.log("用户授权了位置")
					uni.getLocation({
						type: 'gcj02',
						success: function(res) {
							let location = {
								longitude: res.longitude,
								latitude: res.latitude
							}
							let locationJson = JSON.stringify(location)
							//	比较用户当前位置信息,如果位置信息和之前的位置信息不一致,则更新
							//	赋值位置信息
							_this.location = location
							if (oldLocationJson != locationJson) {
								uni.setStorageSync("location", locationJson)
								_this.mescroll.resetUpScroll()
							}
						},
						fail: (err) => {
							uni.showModal({
								title: '',
								content: '请在系统设置中打开定位服务',
								confirmText: '确定',
								success: function(res) {}
							})
						}
					})
				},
				fail: (err) => {
					console.log("用户拒绝了位置")
					this.openSettingPage()
				}
			})

2、uniapp支付宝小程序端

由于支付宝小程序uni.authorize接口不支持,所以需要区分写。也可以都使用下面的支付宝小程序端的代码。

// #ifdef MP-ALIPAY
			uni.getLocation({
				type: 'gcj02',
				success: function(res) {
					let location = {
						longitude: res.longitude,
						latitude: res.latitude
					}
					let locationJson = JSON.stringify(location)
					//	比较用户当前位置信息,如果位置信息和之前的位置信息不一致,则更新
					//	赋值位置信息
					_this.location = location
					if (oldLocationJson != locationJson) {
						uni.setStorageSync("location", locationJson)
						_this.mescroll.resetUpScroll()
					}
				},
				fail: (err) => {
					uni.getSetting({
						success(res) {
							if(res.scope && res.scope.userLocation) {
								uni.showModal({
									title: '',
									content: '请在系统设置中打开定位服务',
									confirmText: '确定',
									success: function(res) {}
								})
								console.log("授权了地理位置,没有获取到用户位置信息,设备定位未打开")
							} else {
								_this.openSettingPage()
								console.log("没有授权地址位置,没有获取到用户位置信息。需要用户打开授权")
							}
						},
						fail(err) {
							console.log(err)
						}
					})
				}
			})
			// #endif
  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值