uniapp获取定位导致APP闪退
刚开始用setInterval定时1秒获取地图定位,因为uni.getLocation经常会返回失败,导致整个定时器错乱闪屏崩溃。
本页面有一个webview,通过evalJS执行webview嵌套页面的方法。
<web-view @message="getMessage" v-if="url" :src="url"></web-view>
错误代码:
this.time = setInterval(() => {
if(!this.wv){
let wv = currentWebview.children()[0];
this.wv = wv;
}
// console.log(currentWebview,"currentWebview---------------111",this.wv)
this.setVersion();
}, 1000);
setVersion() {
uni.getLocation({
type: 'gcj02',
altitude: true,
success:(res)=> {
// longitude:res.longitude,
// latitude:res.latitude,
this.wv.evalJS("setVersion('" + JSON.stringify(res) + "')");
}
});
},
优化后代码,setInterval替换成setTimeout,根据uni.getNetworkType返回网络正常标识来决定间隔时间。
setTimeout(() => {
this.startgetLocation()
}, 50)
// 获取定位信息
async startgetLocation() {
let that = this;
let delay = 3000;//定时器时间间隔3s
let delay_seek = 15000;//如果网络异常,增加定时器时间间隔15s
let isNetCon = true;//网络正常
uni.getNetworkType({
success: res => {
if (res.networkType === 'none') {
isNetCon = false;
}
}
});
if (isNetCon) {
try {
await that.setVersion();//调取定位接口
} catch (e) {
delay = delay + delay_seek;
}
} else {
delay = delay + delay_seek;
}
if (this.time) clearTimeout(this.time);//清除定时器
this.time = setTimeout(function() {
that.startgetLocation();
}, delay);
},
//调取定位接口
setVersion() {
let that = this;
return new Promise((resolve, reject) => {
uni.getLocation({
type: 'gcj02',//默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
altitude: true,
geocode: true,
// highAccuracyExpireTime: 100, // 需要设置highAccuracyExpireTime,在规定时间内返回当前最高精度的经纬度
success:(res)=> {
if(!that.wv){
let currentWebview = that.$scope.$getAppWebview();
let wv = currentWebview.children()[0];
that.wv = wv;
}
if(that.wv){
that.wv.evalJS("setVersion('" + JSON.stringify(res) + "')");
}
resolve('suc');
},
fail: function(err) { //定位失败
// console.log('获取失败')
reject('err');
}
});
})
},
前端大牛的路上

浙公网安备 33010602011771号