微信小程序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();
  }
})

最后注意清除定时器:

相关推荐
鄃鳕2 小时前
C++坑系列,C++ std::atomic 拷贝构造函数问题分析与解决方案
java·javascript·c++
Never_Satisfied3 小时前
在JavaScript / HTML中,实现`<iframe>` 自适应高度
开发语言·javascript·html
CChenhire3 小时前
教育机构作图:含拼团 / 课程封面模板,适配小程序
小程序
低代码布道师3 小时前
少儿舞蹈小程序(21)我的页面搭建
低代码·小程序
koooo~5 小时前
Vue3中的依赖注入
前端·javascript·vue.js
细节控菜鸡8 小时前
【2025最新】ArcGIS for JS二维底图与三维地图的切换
javascript·arcgis
FuckPatience9 小时前
Vue 中‘$‘符号含义
前端·javascript·vue.js
光影少年17 小时前
vue打包优化方案都有哪些?
前端·javascript·vue.js
木易 士心20 小时前
Ref 和 Reactive 响应式原理剖析与代码实现
前端·javascript·vue.js