小程序获取位置时,在manifest.json文件中小程序配置打开定位申请,再切换到源码试图在'mp-weixin'中加入
"requiredPrivateInfos": ["getLocation", "chooseLocation"]
我是用的高德地图获取周围建筑物名称,在页面中获取位置
onLoad() {
this.amapPlugin = new amap.AMapWX({
//填写高德地图的key
key: this.$gaodeKey,
});
},
onShow() {
//每次进入页面获取一下当前位置
this.getRegeo()
}
获取位置的方法:在methods中
获取经纬度使用uniAPI,获取周边信息使用高德地图,因为uniAPI获取的经纬度比高德的精准
getRegeo() {
let that = this
//使用uni的方法获取经纬度
uni.authorize({
scope: 'scope.userLocation',
success: res => {
that.permissions = true
uni.getLocation({
type: 'gcj02',
geocode:true,
success: function(res) {
// 保留小数点后6位
that.latitude = res.latitude.toFixed(6)
that.longitude = res.longitude.toFixed(6)
let la1 = res.latitude.toFixed(6)
let lo1 = res.longitude.toFixed(6)
let isDistanceList = that.rulesDataInfo.locationList.map((item,index) => {
let la2 = Number(item.latitude)
let lo2 = Number(item.longitude)
return that.distance(la1, lo1, la2, lo2) <= item.locationScope
})
//isRange 是声明的变量,用来确定当前位置是否在规定的范围中
that.isRange = !!isDistanceList.find((item) => {
// 如果没有在范围内返回undefined
return item == true
})
},
fail:function(err){
console.log('定位出差错了' + JSON.stringify(err))
}
});
//这个是高德地图的方法获取周围建筑物的名称
this.amapPlugin.getRegeo({
success: (data) => {
this.locationName = data[0].desc;
},
});
},
fail: error => {
// console.log('没同意权限', error)
if(!this.permissions){
this.openConfirm()
}
}
})
},
这里使用uni.getLocation方法获取经纬度,并使用gcj02定位,因为在使用过程中发现高德地图的定位经纬度存在偏差,所以换成了uni的方法,其中la1,lo1是当前用户的经纬度,la2,lo2是我后台返回的经纬度,方法distance()是我判断两个经纬度之间直线距离的方法,传入四个参数
fail中返回失败的原因,判断permissions的值来判断是不是因为没有位置权限
distance方法:
distance(la1, lo1, la2, lo2) {
// la1·lo1是用户位置 la2·lo2是规则定的位置
var La1 = la1 * Math.PI / 180.0;
var La2 = la2 * Math.PI / 180.0;
var La3 = La1 - La2;
var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(
Math.sin(Lb3 / 2), 2)));
s = s * 6378.137; //地球半径
s = Math.round(s * 10000) / 10000 * 1000;
// console.log("两点直线距离m:",s);
return s;
},
因为获取用户位置需要授权,当用户没有授权时就需要提示用户获取权限
openConfirm() {
return new Promise((resolve, reject) => {
uni.showModal({
title: '请求授权当前位置',
content: '打卡功能需要获取地理位置信息',
success: res => {
if (res.confirm) {
uni.openSetting().then(res => {
if (res[1].authSetting['scope.userLocation'] === true) {
// console.log('同意了权限:', res)
//使用一个变量来保存获取到权限的状态
this.permissions = true
this.getRegeo()
}
})
} else if (res.cancel) {
// console.log('用户点击了取消')
}
},
})
})
},
效果如图: