微信小程序 uniapp 点击获取用户实时当前位置进行定位

3 篇文章 0 订阅
1 篇文章 0 订阅

步骤一:该函数(authorization)是用来触发获取为信用户当前位置(getWxLocation)和用户位置授权(toSetting)的:

async authorization() {
				let self = this
				try {

					await this.getWxLocation() //等待
				} catch (error) {
					wx.showModal({
						title: '温馨提示',
						tip: '获取权限失败,需要获取您的地理位置才能为您提供更好的服务!是否授权获取地理位置?',
						showCancel: true,
						confirmText: '前往设置',
						cancelText: '取消',
						sureCall() {
							self.toSetting()
						},
						cancelCall() {}
					})
					return
				}
			},

步骤二:获取用户当前位置信息

getWxLocation() {
				wx.showLoading({ //显示加载
					title: '定位中...',
					mask: true,
				})
				return new Promise((resolve, reject) => {
					let _locationChangeFn = (res) => {
						console.log('location change------------------------------------------',
							res)
						this.latitude = +(res.latitude);
						this.longitude = +(res.longitude);
						console.log("lat-------", this.latitude, "lon--------", this.longitude);
						this.moveToLocation(this.latitude, this.longitude);
						wx.setStorageSync('userLocation', res)
						wx.hideLoading()
						wx.offLocationChange(_locationChangeFn)
					}
					wx.startLocationUpdate({ //开启小程序进入前台时接收位置消息
						success: (res) => {
							console.log("res-------", res);
							wx.onLocationChange(_locationChangeFn);
							resolve();
						},
						fail: (err) => {
							console.log('获取当前位置失败', err);
							wx.hideLoading();
							reject();
						}
					})
				})
			},

注意:像wx.startLocationUpdate, wx.onLocationChange等接口是需要到微信公丛平台进行申请权限的。

步骤三:位置用户权限
          

  toSetting() {
                let self = this
                wx.openSetting({ //设置界面只会出现小程序已经向用户请求过的权限
                    success(res) {
                        console.log(res)
                        if (res.authSetting["scope.userLocation"]) {
                            // res.authSetting["scope.userLocation"]为true时表示用户已同意获得定位信息,此时调用getlocation可以拿到信息
                            self.authorization()
                        }
                    }
                })
            },

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值