uniapp vue 获取定位 当前位置信息 uni.getLocation
因为项目每次页面一打开就触发uni.getLocation,导致小程序页面会变得加载缓慢卡顿,
解决方案:首先我们进入首页设置定时任务,首次进来的时候进行加载一次,设置固定的时间在规定的时间之内不触发,避免频繁加载数据接口,
页面一打开就立即调用
onLoad() {
this.checkAndRequestLocation();
}
methods: {
async checkAndRequestLocation() {
try {
// 检查用户是否首次进入页面
const lastRequestTime = uni.getStorageSync('lastRequestTime');
if (!lastRequestTime || (Date.now() - lastRequestTime > 60 * 60 * 1000)) {
// 用户是首次进入,或者距离上次请求已超过60分钟
this.firstTime = true;
const res = await uni.getLocation({
type: 'wgs84',
success: (location) => {
this.location = location;
// 存储地理位置信息和时间戳
uni.setStorageSync('location', location);
uni.setStorageSync('lastRequestTime', Date.now());
var url = 'https://restapi.amap.com/v3/geocode/regeo?location=' + this
.location.longitude + ',' +
this.location.latitude +
'&key=3c5b5ad0458b3cdb553b3b87ons=base'; //换成自己的高德key值
uni.request({
url: url,
success: (res) => {
//详细地址信息
if (res.statusCode == 200 && res.data.info == 'OK') {
var city = res.data.regeocode.addressComponent.city
if (city.length == 0) {
var city = res.data.regeocode.addressComponent
.province
}
// 获取当前的城市地址
var _that = this
request.httpRequest({
url: '/api/region/getid?name=' + city,
method: 'get'
}).then(res => {
if (res.code == 1) {
// 成功后的具体操作
}
})
}
}
});
},
fail: (err) => {
if (uni.getStorageSync('agree') == true) {
uni.showModal({
title: '是否授权当前位置',
content: '需要获取你的地理位置,请确认授权,否则无法获取你所需要的数据',
confirmText: "确认",
cancelText: '取消',
success: (res) => {
if (res.confirm) {
console.log('同意')
uni.openSetting({
success: (res) => {
this.getOpenLocation();
}
})
} else {
console.log('拒绝')
this.checkAndRequestLocation();
return false;
}
}
})
}
console.error('获取地理位置失败:', err);
return false;
}
});
} else {
// 检索之前存储的地理位置信息
this.location = uni.getStorageSync('location');
this.startPosiName = uni.getStorageSync('startPosiName');
}
} catch (error) {
console.error('检查或请求地理位置时发生错误:', error);
}
},
}
总结:首先需要先获得用户的同意隐私协议,获得地理位置授权,在调用uni.getLocation 进行后续的逻辑判断