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

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);
					}
				});
			}
		}
	});
}

猜你喜欢

转载自blog.csdn.net/qq_37967380/article/details/123695302