startLocationUpdateBackground这个api,在手机长时间锁屏(半个小时)之后onLocationChange这个方法的回调返回的经纬度不会变化,亮屏之后又会恢复,但是再次锁屏之后又会出现之前定位不更新的情况,这个时候手机是在信号很好的地方,之后只要是锁屏定位的经纬度就不会再变化,但是onLocationChange这个回调一直都有返回数据,只是经纬度不再更新,小程序已发布上线,没做复杂逻辑,都是获取到位置直接返回,并且官方文档要求开启的位置权限都已启用,在小程序后台也有申请通过这个api接口能力,用户设置的位置权限也是使用小程序时和离开后都允许
最下面这张图是我从onLocationChange这个api的回调中拿到数据存到后台数据库的截图

https://developers.weixin.qq.com/s/z9Gdkum78r3f
我的代码片段是从uniapp编辑过来的,我单独重新写到新的代码片段比较麻烦,我只能提供到我的具体的实现方法
startTracking() {
if (!this.areaId) {
return
}
this.tracking = true
const startFn =
typeof uni.startLocationUpdateBackground === "function" ?
uni.startLocationUpdateBackground :
uni.startLocationUpdate
startFn({
success: () => {
// 解绑旧监听
// if (typeof uni.offLocationChange === "function" && this.wxLocationListener) {
// uni.offLocationChange(this.wxLocationListener)
// }
uni.onLocationChange(res => {
this.handleLocation(res)
})
},
fail: err => {
console.error("启动定位失败:", err)
uni.showToast({
title: "定位启动失败,请确保已开启后台定位功能,并重新尝试",
icon: "none"
})
this.tracking = false
}
})
},
async handleLocation(resPoint) {
const currentTime = Date.now()
// 第一次直接上传
if (this.first) {
this.first = false
await this.handleReceive(resPoint)
this.lastTime = currentTime
return
}
// 检查时间间隔
if (currentTime - this.lastTime < this.receiveTime * 1000) {
console.log(`跳过上传,还需等待 ${this.receiveTime - (currentTime - this.lastTime) / 1000} 秒`)
return
}
// 执行上传
await this.handleReceive(resPoint)
this.lastTime = currentTime
},
async handleReceive(resPoint) {
const timeSinceLastUpload = (Date.now() - this.lastTime) / 1000
console.log(`执行上传:距离上次上传 ${timeSinceLastUpload.toFixed(1)} 秒,设定间隔 ${this.receiveTime} 秒`)
const userPoint = {
latitude: Number(resPoint.latitude),
longitude: Number(resPoint.longitude)
}
const inArea = this.isPointInPolygon(userPoint, this.polygonPoints)
let params = {
workerId: this.userDetail.user_id,
siteId: this.areaId,
latitude: Number(resPoint.latitude),
longitude: Number(resPoint.longitude),
timestamp: Date.now(),
isEnter: Number(inArea)
}
const res = await this.$u.api.receiveLocation(params)
this.trackedPoints.push(userPoint)
this.drawPathLine(this.trackedPoints)
},