评论

【能力体验】“后台持续定位”接口的使用与踩坑

wx.startLocationUpdateBackground

在小程序基础库 v2.8.0 版本中,新增了小程序后台持续定位功能,没错就是这个接口 wx.startLocationUpdateBackground(Object object)。对于一些有这方面需求的项目来说,这无疑是个好消息!刚好我有个项目刚好需要用到这个功能,这里就分享一下使用的体验吧。

一、使用前提醒

要使用这个能力,官方文档有以下提醒:
1、基础库 2.8.0 开始支持,低版本需做兼容处理。
2、调用前需要 用户授权 scope.userLocationBackground
(需要写一个button供用户点击)

除此之外,你还需要知道:
这个接口仅支持在真机上调试!
因此写代码时可以先用wx.startLocationUpdate(前台时接收位置消息)替代,在运行没问题后再换回并在真机测试。

二、使用时感受

微信团队在公众号里说“满足线路导航、路线记录等服务场景下,小程序需要长时间持续定位来提供服务”,但在实际情况中是,小程序很难实现所谓的“长时间”(有时甚至不到5分钟)。这样就会导致我们记录的数据还没来得及上传就丢失了。

当我发现这个问题,第一时间是抱怨为什么小程序销毁前不能给我们返回一个提醒。但思考后才理解:微信APP自身都不能确保“长时间”在后台运行,还怎么样保证小程序的“长时间”运行呢?(如被一些软件清理了)

三、使用后经验

既然无法避免突发性关闭,又不宜频繁上传地点数据。那么,我们就只能用到缓存了!以实现类似断线重连的功能。

实现效果:

代码:(仅供参考)


var points_map = [ ]  // 实时绘制地图
var points_yun = [ ]  // 云开发需要的格式
var point

Page({

  data: {
    polyline: [{
      points: points_map,
      color: '#FFA500',
      width: 3
    }],
  },

  onLoad: function (options) {
    var that = this
    wx.getStorage({ 
      key: 'TimeStamp',
      success(res) { 
        console.log('有缓存')
        wx.getStorage({
          key: 'points_yun',
          success(res) { points_yun = res.data }
        })
        wx.showModal({
          content: '检测到您有一个未完成的巡护记录!',
          cancelText: '不保存',
          cancelColor: '#DC143C',
          confirmText: '继续巡护',
          confirmColor: '#228B22',
          success(k) {
            if (k.confirm) {
              console.log('用户点击确定-继续巡护')
              that.setData({ TimeStamp: res.data })
              that.GoContinue()
            } else if (k.cancel) {
              console.log('用户点击取消-不保存')
              wx.removeStorage({ key: 'TimeStamp' }) //删缓存
              wx.removeStorage({ key: 'points_yun' })
              points_yun = []
            }
          }
        })
      }, fail(res) {
        console.log('无缓存')
        points_yun = []
      }
    })
  },


  Go: function () { // 开始巡护(首次)
    var that = this
    wx.startLocationUpdateBackground({
      success(res) {
        var TimeStamp = (new Date()).valueOf()
        that.GetNowGeo()
        wx.setStorage({  //设置缓存(TimeStamp)
          key: "TimeStamp",
          data: TimeStamp
        })
      },
      fail() {
      // 这里弹窗引导用户授权使用地理位置
      }
    })
  },
  GoContinue: function () {  // 开始巡护(再续)
    var that = this
    wx.startLocationUpdateBackground({
      success(res) {
        that.GetNowGeo()
      },
      fail() {
      // 这里弹窗引导用户授权使用地理位置
      }
    })
  },

  End: function () {
    var that = this
    wx.stopLocationUpdate()
    clearInterval(this.data.setInter)
    wx.showModal({
      title: '',
      content: '是否要上传数据?',
      success(res) {
        if (res.confirm) {
          that.updateGeo()
        }
      }
    })
  },

  GetNowGeo: function () {
    var that = this
    wx.onLocationChange(function (res) {
      point = { latitude: res.latitude, longitude: res.longitude }
    })
    this.data.setInter = setInterval(function () {
      if (points_map.length == 0) {  
        points_yun.push([])
      } 
      points_map.push(point); //画地图
      that.setData({
        'polyline[0].points': points_map
      })
      var n = [point.longitude, point.latitude]  // 云开发数据库需要的格式
      var r = points_yun.length - 1
      points_yun[r].push(n) 
      wx.setStorage({  // 设置缓存(路程数据)
        key: "points_yun",
        data: points_yun
      })
    }, 6000);
  },

  updateGeo: function () {
    var that = this
    wx.showLoading({
      title: '数据上传中',
    })
    db.collection('patrol_geo').add({  // 云开发上传
      data: {
        location: {
          type: 'MultiLineString',
          coordinates: points_yun
        }
      },
      success: res => {
        wx.showToast({
          title: '上传成功'
        })
        wx.removeStorage({ key: 'TimeStamp' }) // 清理缓存
        wx.removeStorage({ key: 'points_yun' })
      },
      fail: res => {
        wx.showToast({
          title: '上传失败,请重新操作!'
        })
        console.log(res)
      }
    })
  },

})

最后一次编辑于  2019-09-26  
点赞 9
收藏
评论

1 个评论

  • 晴天不动雨夜黑₆⁶₆
    晴天不动雨夜黑₆⁶₆
    2020-08-12

    如何在微信界面,把你的后台定位悬浮图标叉掉,立马再进小程序,此时小程序还没置于后台5分钟,onload是不会执行的,请问你怎么继续定位呢

    2020-08-12
    赞同
    回复
登录 后发表内容