uni-app中实现位置授权以及打开地图选择位置功能

uni-app中实现位置授权以及打开地图选择位置功能

注意点:this的指向问题,是否指向vc决定你能否拿到data里面的数据

template

<button @click="chooseLocation">打开地图选择位置</button>

js

export default {
    
    
	data() {
    
    
		return {
    
    
			address: ''
		};
	},
	methods: {
    
    
		// 打开地图选择位置
		chooseLocation() {
    
    
		// 此处拿到的this才是指向vc
			const that = this;
			// 发起授权请求
			uni.authorize({
    
    
				// 授权权限
				scope: 'scope.userLocation',
				success() {
    
    
					// 打开地图选择位置
					uni.chooseLocation({
    
    
						success(res) {
    
    
							console.log('位置名称:' + res.name);
							console.log('详细地址:' + res.address);
							console.log('纬度:' + res.latitude);
							console.log('经度:' + res.longitude);
							that.address = res.address;
							// 此处如果直接使用this, 是无法获取到data里面的数据的,因为此处this指向不是vc
						}
					});
				},
				fail(e) {
    
    
					console.log(e);
					let errMsgTit = '';
					if (e.errMsg === 'authorize:fail 系统错误,错误码:-12006,auth deny') {
    
    
						errMsgTit = '你已拒绝授权,是否跳转至设置页面开启权限';
					}
					uni.showModal({
    
    
						title: '提示',
						content: `${
      
      errMsgTit}`,
						success(res) {
    
    
							if (res.confirm) {
    
    
								// 获取设置页面权限信息
								uni.getSetting({
    
    
									success(res) {
    
    
										console.log(res.authSetting);
										// 判断是否开启获取位置权限
										if (!res.authSetting['scope.userLocation']) {
    
    
											// 如果没有开启,点击确认后打开设置页面
											uni.openSetting({
    
    });
										}
									}
								});
								console.log('用户点击确定');
							} else if (res.cancel) {
    
    
								console.log('用户点击取消');
							}
						}
					});
				}
			});
		}
};
</script>

效果图
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/JunVei/article/details/126612206