1.引入微信jsskd文件
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
2.调用后端接口传递当前页面的URL路径(去除#及其后面的部分)
function handURL(){
return window.location.href.split('#')[0]; //当前页面URL
}
function handSignature(){
let url = handURL();
LoginApi.getStamp( {
url:url,
}).then((res)=>{
console.log(res)
handSignatureValue.value = res.data;
//返回签名signature,生成签名的随机字符串nonceStr,生成签名的时间戳timestamp
}).catch((err)=>{
showSnackbar(err)
})
}
3.使用步骤2所获取到的数据进行调用JS-SDK前需要进行的注入权限验证配置 (这一步通常在挂载阶段完成)
const initWechatSDK=()=>{
let timestamp = handSignatureValue.value.xtiftimestamp ;//生成签名的随机字符串
let nonceStr = handSignatureValue.value.xtifnonce; //生成签名的时间戳
let signature = handSignatureValue.value.xtifsignature;//签名
wx.config({
// beta: true, //调用wx.invoke形式的接口值时值必须为true
debug: false, //调试模式
appId: 'wl2bee594e73', //cropID
timestamp: parseInt(timestamp),
nonceStr: nonceStr,
isHighAccuracy: true, //高精度
signature: signature,
jsApiList: ['getLocation'] //需要使用的JS接口列表 getLocation-获取地理位置接口
});
wx.ready(() => {
});
wx.error((err) => {
console.log(err);
});
}
4.实现获取位置信息方法,拿到返回的经纬度
//获取位置信息
const getLocation=()=>{
return new Promise((resolve, reject) => {
wx.getLocation({
type: 'wgs84',
success: (posRes) => {
console.log(posRes)
resolve({
lat: posRes.latitude,
lng: posRes.longitude
});
},
fail: (err) => {
console.log(err);
reject({ errorMessage: '获取经纬度失败,确认是否开启位置' });
}
});
})
}
5.利用setInterval定时器实现持续定位(每半分钟调用后端接口上传一次当前经纬度信息)
//开启持续定位
const StartAutoLBS= () => {
getLocation().then((res)=>{
sendAutoLbs( res.lat, res.lng, locationId.value, locationUserId.value)
}).catch((err)=>{ console.log(err)});
//确保当前页面只存在这一个lbaTimer定时器
if( lbaTimer.value){
lbaTimer.value = null;
clearInterval( lbaTimer.value);
}
lbaTimer.value = setInterval(async () => {
getLocation().then((res)=>{
sendAutoLbs( res.lat, res.lng, locationId.value, locationUserId.value)
}).catch((err)=>{
console.log(err)
});
}, 1000 * 30);
}
6.关闭持续定位,直接清除定时器即可