微信小程序app.js中每30秒调用一次wx.getLocation
代码:
const auth = require('./utils/auth.js'); // 引入 auth.js
// app.js
App({onLaunch() {// 原有登录检查逻辑const isLoggedIn = auth.checkLogin();if (!isLoggedIn) {wx.removeStorageSync('token');wx.removeStorageSync('userInfo');wx.reLaunch({ url: '/pages/login/login' }); }// 新增定时定位逻辑this.startLocationInterval();},startLocationInterval() {// 立即执行一次this.getAndCacheLocation();// 设置30秒定时器this.locationTimer = setInterval(() => {this.getAndCacheLocation();}, 30000);},getAndCacheLocation() {wx.getLocation({type: 'wgs84',success: (res) => {console.log("lat="+res.latitude+'&lon='+res.longitude)wx.setStorageSync('lastLocation', {latitude: res.latitude,longitude: res.longitude,timestamp: new Date().getTime()});},fail: (err) => {console.error('定位失败', err);}});},onHide() {// 小程序进入后台时清除定时器if (this.locationTimer) {clearInterval(this.locationTimer);}},onUnload() {// 双重保险if (this.locationTimer) {clearInterval(this.locationTimer);this.locationTimer = null;}},onShow() {// 小程序回到前台时重启定时器this.startLocationInterval();}
})
最后注意清除定时器: