微信小程序(uniapp)获取用户位置信息及选择位置

13 篇文章 0 订阅
12 篇文章 0 订阅

1. 开发前准备

  • 注册微信小程序账号并配置相关信息;
  • 注册腾讯地图开放平台并完成应用创建等;
  • 下载qqmap-wx-jssdk.min.js放到项目中;

2. 获取用户当前位置wx.getLocation

// #ifdef MP-WEIXIN
this.initLocationInfoMP();
// #endif

//初始化位置
initLocationInfoMP() {
	const _this = this;
	wx.getLocation({
		//type: 'gcj02', //wgs84返回gps坐标,gcj02返回可用于wx.openLocation 的坐标
		success: res => {
			// 将获取到的 经纬度传值给 formatAddress 解析出 具体的地址
			_this.formatAddress(res.latitude, res.longitude);
		},
		fail: res => {
			_this.$mHelper.toast('获取位置信息失败', 5000);
		}
	});
},
//解析通过微信获取到的经纬度地址
async formatAddress(latitude, longitude) {
	const _this = this;
	
	// 通过申请的key生成wxMap实例
	let map = new wxMap({key: "腾讯地图KEY"});
	// reverseGeocoder 为QQMapWX解析经纬度的方法
	map.reverseGeocoder({
		location: {latitude, longitude},
		success: res => {
			//res.result即解析得到的位置信息
		},
		fail: () => {
			_this.$mHelper.toast('获取位置信息失败', 5000);
		}
	})
}

3. 选择位置wx.chooseLocation(打开地图选择位置并返回数据)

//切换位置点击事件
chooseLocationMP() {
	const _this = this;
	wx.getSetting({
		success(res) {
			if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
				uni.showModal({
					title: '是否授权当前位置',
					content: '你的位置信息将用于应用展示的周边商家,请确认授权',
					success: function(res) {
						if (res.cancel) {
							_this.$mHelper.toast('取消授权', 2000);
							return;
						}
						wx.openSetting({
							success: function(data) {
								if (data.authSetting["scope.userLocation"] !== true) {
									_this.$mHelper.toast('授权失败', 5000);
									return;
								}
								_this.$mHelper.toast('授权成功', 2000, 'success');
								_this.initLocationInfoMP();
							}
						})
					}
				})
			} else {
				wx.chooseLocation({
					success:(res) => {
						//res.latitude纬度, res.longitude经度
						//调用formatAddress解析经纬度得到位置信息
					},
					fail:() => {
						_this.$mHelper.toast('获取位置信息失败', 5000);
					}
				});
			}
		}
	});
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值