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

最后注意清除定时器:

相关推荐
A_nanda2 小时前
根据AI提示排查vue前端项目
前端·javascript·vue.js
~无忧花开~2 小时前
React状态管理完全指南
开发语言·前端·javascript·react.js·前端框架
@大迁世界3 小时前
1.什么是 ReactJS?
前端·javascript·react.js·前端框架·ecmascript
前端Hardy6 小时前
Wails v3 正式发布:用 Go 写桌面应用,体积仅 12MB,性能飙升 40%!
前端·javascript·go
Highcharts.js6 小时前
Highcharts React v4 迁移指南(下):分步代码示例与常见问题解决
javascript·react.js·typescript·react·highcharts·代码示例·v4迁移
Laurence6 小时前
Qt 前后端通信(QWebChannel Js / C++ 互操作):原理、示例、步骤解说
前端·javascript·c++·后端·交互·qwebchannel·互操作
Pu_Nine_96 小时前
JavaScript 字符串与数组核心方法详解
前端·javascript·ecmascript
这是个栗子6 小时前
前端开发中的常用工具函数(六)
javascript·every
2501_915918416 小时前
苹果App Store上架审核卡住原因分析与解决方案指南
android·ios·小程序·https·uni-app·iphone·webview
kyriewen6 小时前
异步编程:从“回调地狱”到“async/await”的救赎之路
前端·javascript·面试