由于wx.getLocation新版有了频率限制,好好的定位接口不能再频繁调用。只能用新版的wx.onLocationChange,但是新版的wx.onLocationChange必须在2.8.1以上才能使用。最后没办法只能做向下兼容 首先判断当前微信的版本号,这里我用了当初判断ios机型的api来获取版本号,存储在全局里面
let capsuleObj = wx.getMenuButtonBoundingClientRect();
wx.getSystemInfo({
success: (res) => {
if(res.platform == "ios" || res.system.indexOf('iOS') > -1 || res.system.indexOf('macOS') > -1){
this.globalData.isIos = true;
}
var statusBarHeight = res.statusBarHeight;
this.globalData.headerHeight = statusBarHeight + capsuleObj.height + (capsuleObj.top - statusBarHeight) * 2;
let version = res.SDKVersion;
this.globalData.version = version.replace(/\./g, "");
},
fail() {
}
})
然后在获取定位的页面
getlocation() {
wx.getLocation({
type: 'gcj02',
success: res => {
this.data.signInfo.signLongitude = res.longitude;
this.data.signInfo.signLatitude = res.latitude;
},
fail: error => {
wx.showModal({
title: '提示',
content: '定位失败,请检查是否授权定位',
showCancel: false,
success:res=> {
this.toSetting();
}
})
}
})
if (this.data.localTimer) {
clearInterval(this.data.localTimer)
this.data.localTimer = null;
}
if(app.globalData.version > 2160){
this.data.localTimer = setInterval(() => {
this.getWxLocation()
}, 3000)
}else {
this.data.localTimer = setInterval(() => {
wx.getLocation({
type: 'gcj02',
success: res => {
this.data.signInfo.signLongitude = res.longitude;
this.data.signInfo.signLatitude = res.latitude;
},
fail: error => {
}
})
}, 3000)
}
},
getWxLocation() {
let that = this;
try {
let _locationChangeFn = (res) => {
that.data.signInfo.signLongitude = res.longitude;
that.data.signInfo.signLatitude = res.latitude;
wx.offLocationChange(_locationChangeFn)
}
wx.startLocationUpdate({
success: (res) => {
wx.onLocationChange(_locationChangeFn)
},
fail: (err) => {}
})
} catch (error) {
}
},
toSetting() {
let self = this
wx.openSetting({
success(res) {
if (res.authSetting["scope.userLocation"]) {
}
}
})
},
最后别忘了在销毁页面时关闭定时器
onUnload: function () {
if (this.data.localTimer) {
clearInterval(this.data.localTimer);
this.data.localTimer = null;
}
},
|