uni-app 获取当前的地理位置【uni.getLocation(OBJECT)】

uni-app获取当前的地理位置【uni.getLocation(OBJECT)】

  1. 在 manifest.json中配置 permission
    在这里插入图片描述
"permission": {
	"scope.userLocation": {
		"desc": "你的位置信息将用于小程序位置接口的效果展示"
	}
},
  1. 在需要的页面写
// 判断地理位置是否授权
function authorizedPositioning( callBack = ()=>{} ){
	uni.getSystemInfo({ // 获取系统信息
			success(res) {
				let locationEnabled = res.locationEnabled; //判断手机定位服务是否开启
				let locationAuthorized = res.locationAuthorized; //判断定位服务是否允许微信授权
				if (locationEnabled == false || locationAuthorized == false) {
					// GPS 未授权
					callBack("GPSunauthorized");
				} else {
					// GPS 已授权 判断微信定位是否授权
					uni.authorize({
						scope: 'scope.userLocation',
						success() {
							// GPS已授权 微信定位已授权
							uni.getLocation({
								type: 'gcj02',
								success({
									latitude,
									longitude
								}) {
									// latitude; 纬度
									// longitude; 经度
									callBack("Authorized", {
										latitude,
										longitude
									});
								}
							});
						},
						fail() {
							// GPS已授权 微信定位未授权
							callBack("WENXINunauthorized");
							uni.showModal({
								title: '未打开小程序定位',
								content: '找不到您的位置,请开启定位',
								confirmText: '开启定位',
								showCancel: false,
								success: (res) => {
									if (res.confirm) {
										uni.openSetting(); // 打开地图权限设置
									}
								}
							});
						}
					});
				}
			}
	})
}

// 使用promise 判断地理位置是否授权
function authorizedPositioningPromise() {
	return new Promise((resolve, reject) => {
		uni.getSystemInfo({
			success({
				locationEnabled,
				locationAuthorized
			}) {
				// locationEnabled 判断手机定位服务是否开启
				// locationAuthorized 判断定位服务是否允许微信授权
				if (!locationEnabled && !locationAuthorized) {
					// GPS未开启 与 GPS未给微信授权定位服务
					reject("GPSnotOpen");
				} else if (locationEnabled && !locationAuthorized) {
					// GPS已开启 与 GPS未给微信授权定位服务
					reject("GPSauthorization");
				} else if (locationEnabled && locationAuthorized) {
					/* 
						GPS已开启 与 GPS已给微信授权定位服务
						判断微信小程序位置信息是否开启
					*/
					uni.authorize({
						scope: "scope.userLocation",
						success() {
							// 微信小程序位置信息已开启
							uni.getLocation({
								success({
									latitude,
									longitude
								}) {
									// latitude; 纬度
									// longitude; 经度
									resolve({
										latitude,
										longitude
									});
								}
							});
						},
						fail() {
							// 微信小程序位置信息未开启
							reject("weixinPositionNotOpen");
						}
					})
				}
			},
			fail(err) {
				let reg = /request:fail/;
				if (reg.test(err.errMsg)) {
					// 无网络
					reject("noNetWork");
				} else {
					// 请求超时'
					reject("requestTimeOut");
				}
			}
		})
	});
}
  1. 效果图
    在这里插入图片描述
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值