其他分享
首页 > 其他分享> > UNI-APP获取当前位置,出现getLocation:fail [geolocation:7]错误的问题解决

UNI-APP获取当前位置,出现getLocation:fail [geolocation:7]错误的问题解决

作者:互联网

最近遇到一个问题:uni-app在获取定位时,在调试状态下可以正常获取当前位置信息,在云打包之后获取定位时,出现getLocation:fail [geolocation:7]的错误。

经调试后,发现是在申请高德地图KEY时,App的包名填写错误导致的。

正常流程如下:

1、拿到APP包名:

2、申请高德地图key

如何查看证书

keytool -list -v -keystore  E:\my\test.keystore    //后面是证书的路径 写自己的

申请key

 3、在项目清单中配置

4、代码中调用

<template>
	<view>
		<!--导航栏-->
		<cu-custom bgColor="bg-blue" :isBack="true"><block slot="content">现场打卡</block></cu-custom>
		<!--定位信息-->
		<view class="info-pt">
			<view class="row-pt">
				<view class="lt-pt">当前位置:<text class="val-pt">{{address}}</text></view>
				<view class="rt-pt bg-green" @click="getLocation">刷新</view>
			</view>
			<view class="row-pt">
				<view class="lt-pt">距离设备:<text class="val-pt">{{distance}}km</text></view>
				<view class="rt-pt bg-blue" @click="submit">打卡</view>
			</view>
		</view>
		<!--地图-->
		<map class="map" :latitude="latitude" :longitude="longitude" :markers="markers" :scale="scale" @marktap="marktap"  @callouttap="callouttap"></map>
		<!--popup-->
		<uni-popup :show="type === 'showpopup'" mode="fixed" @hidePopup="togglePopup('')">
			<view class="popup-view">
				<text class="popup-title">需要用户授权位置权限</text>
				<view class="uni-flex popup-buttons">
					<button class="uni-flex-item" type="primary" open-type="openSetting" @tap="openSetting">设置</button>
					<button class="uni-flex-item" @tap="togglePopup('')">取消</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	// #ifdef APP-PLUS
	import permision from "@/utils/permission.js"
	// #endif
	
	export default {
		components: {
		    uniPopup
		},
		data() {
			return {
				woInfo: null,
				cmuid: '',
				address: '正在获取当前位置...',
				distance: '',
				longitude: 113.867476,
				latitude: 22.786265,
				scale: 13,
				markers: [],
				type: '',
				dlocation: null,
				dposNaN: false,
			}
		},
		onLoad(option) {
			//获取cmuid
			this.cmuid = uni.getStorageSync('cmuid');
			//获取传递的参数
			this.woInfo = JSON.parse(decodeURIComponent(option.item));
			//获取设备位置
			this.getDeviceLocation();
		},
		methods: {
			/*地图定位*/
			marktap(e) {
			},
			callouttap(e) {
			},
			/*获取定位*/
			togglePopup(type) {
			    this.type = type;
			},
			showConfirm() {
			    this.type = 'showpopup';
			},
			hideConfirm() {
			    this.type = '';
			},
			async getLocation() {
			    // #ifdef APP-PLUS
			    let status = await this.checkPermission();
			    if (status !== 1) {
			        return;
			    }
			    // #endif
			    // #ifdef MP-WEIXIN || MP-TOUTIAO || MP-QQ
			    let status = await this.getSetting();
			    if (status === 2) {
			        this.showConfirm();
			        return;
			    }
			    // #endif
			    this.doGetLocation();
			},
			doGetLocation() {
				this.api.showComLoading();
				//获取当前位置
			    uni.getLocation({
					type: 'gcj02',
					geocode: true,
			        success: (res) => {
						//当前地址
						this.address = res.address.province?res.address.province:'';
						this.address += res.address.city?res.address.city:'';
						this.address += res.address.district?res.address.district:'';
						this.address += res.address.street?res.address.street:'';
						this.address += res.address.streetNum?res.address.streetNum:'';
						this.address += res.address.poiName?res.address.poiName:'';
						//当前经纬度
						this.longitude = res.longitude;
						this.latitude = res.latitude;
						if(this.dlocation){
							//计算距离
							var dist = this.getDistance(res.latitude, res.longitude, this.dlocation.lat, this.dlocation.lng);
							this.distance = dist.toFixed(2);
						}else{
							//设备经纬度不存在
							if(this.dposNaN){
								this.api.showComToast('设备地址不存在');
							}else{
								this.getDeviceLocation();
							}
						}
						//marks
						let marks = [];
						let cmark = {};
						cmark.latitude = res.latitude;
						cmark.longitude = res.longitude;
						cmark.width = 24;
						cmark.height = 32;
						cmark.id = 1;
						//当前位置
						cmark.iconPath = '/static/images/zb.png';
						marks.push(cmark);
						let dmark = {};
						dmark.latitude = this.dlocation.lat;
						dmark.longitude = this.dlocation.lng;
						dmark.width = 24;
						dmark.height = 32;
						dmark.id = 2;
						//当前位置
						dmark.iconPath = '/static/images/zb_r.png';
						marks.push(dmark);
						this.markers = marks;
			        },
			        fail: (err) => {
			            // #ifdef MP-BAIDU
			            if (err.errCode === 202 || err.errCode === 10003) { // 202模拟器 10003真机 user deny
			                this.showConfirm();
			            }
			            // #endif
			            // #ifndef MP-BAIDU
			            if (err.errMsg.indexOf("auth deny") >= 0) {
			                uni.showToast({
			                    title: "访问位置被拒绝"
			                })
			            } else {
			                uni.showToast({
			                    title: err.errMsg
			                })
			            }
			            // #endif
			        },
					complete: (e) => {
						this.api.hideComLoading();
					}
			    })
			},
			getSetting: function() {
			    return new Promise((resolve, reject) => {
			        uni.getSetting({
			            success: (res) => {
			                if (res.authSetting['scope.userLocation'] === undefined) {
			                    resolve(0);
			                    return;
			                }
			                if (res.authSetting['scope.userLocation']) {
			                    resolve(1);
			                } else {
			                    resolve(2);
			                }
			            }
			        });
			    });
			},
			openSetting: function() {
			    this.hideConfirm();
			    uni.openSetting({
			        success: (res) => {
			            if (res.authSetting && res.authSetting['scope.userLocation']) {
			                this.doGetLocation();
			            }
			        },
			        fail: (err) => {}
			    })
			},
			async checkPermission() {
			    let status = permision.isIOS ? await permision.requestIOS('location') :
			        await permision.requestAndroid('android.permission.ACCESS_FINE_LOCATION');
			
			    if (status === null || status === 1) {
			        status = 1;
			    } else if (status === 2) {
			        uni.showModal({
			            content: "系统定位已关闭",
			            confirmText: "确定",
			            showCancel: false,
			            success: function(res) {
			            }
			        })
			    } else if (status.code) {
			        uni.showModal({
			            content: status.message
			        })
			    } else {
			        uni.showModal({
			            content: "需要定位权限",
			            confirmText: "设置",
			            success: function(res) {
			                if (res.confirm) {
			                    permision.gotoAppSetting();
			                }
			            }
			        })
			    }
			
			    return status;
			},
			/*百度地图坐标转换成高德坐标gcj02*/
			bMapTransGdMap(lng, lat) {
			      let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
			      let x = lng - 0.0065;
			      let y = lat - 0.006;
			      let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
			      let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
			      let lngs = z * Math.cos(theta);
			      let lats = z * Math.sin(theta);
			      
			      return {
			          lng: lngs,
			          lat: lats        
			      }   
			},
			//获取设备位置
			getDeviceLocation(){
				let para = {
					'cmuid': this.cmuid,
					'id': this.woInfo.id
				}
				this.api.deviceLocation(para).then(res=>{
					if(res.data.msgCode && res.data.msgCode == "0"){
						if(res.data.data.longitude){
							let lnglat = res.data.data;
							this.dlocation = this.bMapTransGdMap(lnglat.longitude, lnglat.latitude);
							//获取当前位置
							this.getLocation();
						}else{
							this.dposNaN = true;
							this.api.showComToast('设备地址不存在');
						}
					}else{
						this.api.showComToast(res.message);
					}
				})
			},
			/*计算两个经纬度的距离(千米)*/
			getDistance(lat1, lng1, lat2, lng2){
				var radLat1 = lat1*Math.PI / 180.0;
				var radLat2 = lat2*Math.PI / 180.0;
				var a = radLat1 - radLat2;
				var b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
				Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
				s = s *6378.137 ;// EARTH_RADIUS;
				s = Math.round(s * 10000) / 10000;
				return s;
			},
			/*打卡提交*/
			submit(){
				//判断是否定位成功
				if(!this.distance){
					this.api.showComToast('正在获取当前位置,请稍后...');
					return;
				}
				//判断是否在打卡范围
				if(this.distance > 5){
					this.api.showComToast('超出打卡范围,请在5km内打卡');
					return;
				}
				//打卡成功
				this.api.showComToast('打卡成功');
				//传参
				uni.$emit('locationinfo',{address: this.address, lng: this.longitude, lat: this.latitude});
				//返回
				setTimeout(()=>{
					uni.navigateBack();
				}, 2000)
			}
		}
	}
</script>

<style lang="scss">
.info-pt{
	background-color: #FFFFFF;
	
	.row-pt{
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1rpx solid #EFEFEF;
		padding: 20rpx 20rpx;
		font-size: 24rpx;
		.lt-pt{
			color: #999999;
			width: 80%;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 1;
			overflow: hidden;
			
			.val-pt{
				color: #007AFF;
			}
		}
		.rt-pt{
			border-radius: 15rpx;
			padding: 10rpx 30rpx;
		}
	}
}

.map{
	width: 750rpx;
	height: calc(100vh - var(--status-bar-height) - 45px - 43px - 43px);
}

.popup-view {
	width: 500rpx;
}

.popup-title {
	display: block;
	font-size: 16px;
	line-height: 3;
	margin-bottom: 10px;
	text-align: center;
}

.popup-buttons button {
	margin-left: 4px;
	margin-right: 4px;
}

.uni-flex {
	display: flex;
	flex-direction: row;
}

.uni-flex-item {
	flex: 1;
}
</style>

 完!!!

标签:status,geolocation,getLocation,res,APP,let,address,uni,Math
来源: https://blog.csdn.net/xialong_927/article/details/120414518