前言

前提:该实例是使用uniapp的小程序 实现的
文章描述:
这里要实现的功能是:
1、点击页面中的一个按钮
2、判断用户是否授权位置信息
3、未授权–>弹出位置授权框;已授权–>进入下一个页面(地址选择页);
4、弹出位置授权框后,是否同意授权
5、同意:得到地址;不同意:–>进入下一个页面(地址选择页)
6、用户不同意位置授权的前提下,用户第二次进入小程序点击这个按钮:弹窗提示用户是否开启位置访问
7、同意:跳转找设置用户开启允许访问设置
8、不同意:–>进入下一个页面(地址选择页)
结果:得到用户当前位置或用户进入地址选择页选择需要的位置


一、创建点击事件的方法

在pages/home/home.vue编写此代码创建点击事件isdingwei(),

<template>
	<view class="location">
		<!-- 定位 -->
		<view class="location-view" @click="isdingwei()">
			<text class="location-text">{{city}}</text>
		</view>
		<!-- end -->
	</view>
</template>
<script>
	export default {
		data() {
			return {
				city: '深圳市'
			}
		},
		methods:{
			isdingwei(){
				//点击事件的方法
			}
		}
	}
</script>

二、判断用户是否授权位置

考虑到在项目中我们可能不止一次地方用到或者方便修改等问题,
1、项目下创建了新的目录存放(utils/indes.js),如图:
在这里插入图片描述
2、在utils/indes.js写一个判断用不是否授权位置的方法authorizedLocation():

export function authorizedLocation(){
	return new Promise((resolve,reject)=>{
		uni.getSetting({
			success:(res)=>{
				// res.authSetting['scope.userLocation'] === undefined  表示 初始化进入,从未授权
				// res.authSetting['scope.userLocation'] === true       表示 已授权
				// res.authSetting['scope.userLocation'] === false      表示 授权拒绝
				if( res.authSetting['scope.userLocation'] === undefined){
					console.log("弹出位置授权框")
					
				}else if(res.authSetting['scope.userLocation'] === true){
					console.log("已经授权")
				}else if(res.authSetting['scope.userLocation'] === false){
					console.log("弹出允许授权设置框")
				}
			}
		})
	})
}

在这里插入图片描述3、在项目中引入,并使用:

<script>
	//引入
	import {authorizedLocation} from '../../../utils/index.js'
	export default {
		data() {
			return {
				city: '深圳市'
			}
		},
		methods:{
			isdingwei(){
				// 判断是否授权
				authorizedLocation()
			}

		}
	}
</script>

在控制台可以看到我们的结果可以看到我们是没有授权过的
在这里插入图片描述

三、弹出位置授权框

1、在(utils/indes.js)下在定义一个方法getLocation()获取用户位置信息:

// 获取用户当前位置
export function getLocation(){
	return new Promise((resolve,reject)=>{
		uni.getLocation({
			type: 'wgs84',
			success:(res)=>{
				resolve(res)
				console.log(res)
				console.log('当前位置的经度:' + res.longitude);
				console.log('当前位置的纬度:' + res.latitude);
			},
			fail:(err)=>{
				reject(err)
				console.log(err)
			}
		})
	})
}

2、在authorizedLocation()方法中调用,如图:
在这里插入图片描述
在方法里面的第一个判断条件里添加代码段:

if( res.authSetting['scope.userLocation'] === undefined){
					// console.log("弹出位置授权框")
					getLocation()
					.then((res)=>{
						// 授权位置成功
						resolve(res)
					})
					.catch((err)=>{
						// 授权位置失败
						reject(err)
						uni.showToast({
							title: '授权位置失败',
							icon: 'none',
							duration: 3000
						})
					})
				}

前提:res.authSetting[‘scope.userLocation’] === undefined 表示 初始化进入,从未授权。结果:
1、点击按钮–>弹出授权框
在这里插入图片描述
2、–>同意
在这里插入图片描述
3、–>不同意
在这里插入图片描述

四、坐标到坐标所在位置的文字描述的转换(逆地址解析)

用户授权成功后,就得了用户位置的经纬度,通过经纬度转换成文字描述,同样我们把实现方法先封装到pages/utils/index.js 下:
1、逆地址解析需要用到地图的AIP,所以移步到腾讯地图做好准备工作,我觉得跟着官方文档做就好了,不过也会有一些坑,我把我遇到的写上:
在这里插入图片描述
1、第一、第二、第四步骤跟着官方文档走就好了
2、第三步,下载好了放到自己的文档的目录下我放在了、/libs的目录下,如图:
在这里插入图片描述
3、申请号的Key:放到项目里(我放在了、config/indes.js),最好放在全局这样修改起来方便,引入看下面
在这里插入图片描述

4、第五步骤中我的项目是vue3,不能个官方文档那样引入

// 腾讯地图秘钥引入
import * as KEY from '../config';


import QQMapWX from '../libs/qqmap-wx-jssdk.js';
const qqmapsdk = new QQMapWX({
  key: KEY.MAP_KEY
})

在看看官方文档的逆地址解析,定义reverseGeocoder (location)函数实现转换:

// 逆地址解析(坐标转具体位置信息)
// location:参数为经纬度{longitude, latitude}
// get_poi:是否返回周边POI列表:1.返回;0不返回(默认)
// poi_options:用于控制Poi列表

export function reverseGeocoder (location) {
  return new Promise((resolve, reject) => {
    qqmapsdk.reverseGeocoder({
      location: location,
      get_poi: 1,
      poi_options: 'policy=1;page_size=20;page_index=1',
      success: res => {
        resolve(res)
      },
      fail: err => {
        reject(err)
        uni.showToast({
          title: err.message,
          icon: 'none',
          duration: 3000
        })
      }
    })
  })
}

5、回到pages/home/home.vue 。在引入上添加 reverseGeocoder,定义getLocationInfo(location)方法调用 reverseGeocoder()

	import {authorizedLocation,reverseGeocoder} from '../../../utils/index.js'
// 根据经纬度得到位置信息
			getLocationInfo(location){
				// console.log("进来没")
				 reverseGeocoder(location)
					.then((res) => {
						console.log('当前位置信息:', res)
						//获取所在的城市
						this.city = res.result.ad_info.city
						})				 
						.catch((err) =>{
				 })
			},
			// end

1、在isdingwei()里面调用getLocationInfo(location):

isdingwei(){
				// 判断是否授权
				authorizedLocation()
				.then((res)=>{
					// 已授权
					// console.log("res里面有什么!!!",res)
					const latitude = res.latitude;
					const longitude = res.longitude;
					let location = { longitude, latitude }
					
					// 根据经纬度得到位置信息
					this.getLocationInfo(location)
					
				})
				.catch(()=>{
					
				})
				
			},

6、已授权位置直接进入下一个页面,在isdingwei()添加代码段:

isdingwei(){
				// 判断是否授权
				authorizedLocation()
				.then((res)=>{
					// 第一次授权
					if(res.errMsg==="getLocation:ok"){
						console.log("res里面有什么!!!",res)
						const latitude = res.latitude;
						const longitude = res.longitude;
						let location = { longitude, latitude }
						
						// 根据经纬度得到位置信息
						this.getLocationInfo(location)
					}else if(res.errMsg==="getSetting:ok"){
					//已授权
						uni.navigateTo({
							url: '../../../../citylist/citylist'
						})
					}
					
					
				})
				.catch(()=>{
					
				})
				
			},

在 authorizedLocation()函数中判断为已授权哪里加上resolve(res):
在这里插入图片描述

五、拒接授权后再次点击按钮跳转到允许访问位置设置

在utils/index.js目录下的authorizedLocation()函数中添加如下代码段
在(else if(res.authSetting[‘scope.userLocation’] === false){ … }){}里面加

	// console.log("弹出允许授权设置框")
					uni.showModal({
						title: '提示',
						content: '是否允许授权位置信息',
						confirmText: '去设置',
						success:(res)=>{
							if(res.confirm){
								uni.openSetting({
									success:(res)=> {
										if (res.authSetting['scope.userLocation']) {
										  resolve(res)
										} else {
										  reject(res)
										  uni.showToast({
										    title: '授权失败',
											icon: 'none',
											duration: 3000
										  })
										}
									},
									fail: (err) => {
									  reject(err)
									  uni.showToast({
									    title: '打开设置异常',
									    icon: 'none',
									    duration: 3000
									  })
									}
								})
							}else {
								reject(res)
								console.log("asjfs 卡号的")
								console.log(res)
							}
								
						},
						fail: err => {
						  reject(err)
						  uni.showToast({
						    title: '弹窗异常',
						    icon: 'none',
						    duration: 3000
						  })
						}
						
					})

在pages/home/home.vue中 isdingwei()方法中添加代码段:

.catch((err)=>{
					if(err.errMsg==="showModal:ok" && err.confirm==false){
						uni.navigateTo({
							url: '../../../../citylist/citylist'
						})
					}
				})

在这里插入图片描述

完成啦!!!!


总结

以上就是今天学习到的一些内容,本文仅仅自己的学习过程的记录,可能有些写的不好的地方,也不够优雅,只是简单的把功能实现了,各位大佬看到有什么不对的地方还望指正,和我一样的新手有什么不懂的地方也可以一起讨论。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐