php实现个人轨迹跟踪,[WebGIS] HTML5跟踪GPS轨迹(5)记录轨迹功能实现

本文介绍如何在Vue应用中结合HTML5的Geolocation API和IndexedDB实现GPS轨迹记录功能。当点击开始记录按钮时,按钮变红,启动定位并循环获取位置信息,存储到IndexedDB的'locations'表中。再次点击则停止定位,清除定时器。定位成功后的坐标信息包括时间戳、纬度、经度、精度等,全部保存在数据库中。
摘要由CSDN通过智能技术生成

前文《HTML5跟踪GPS轨迹(4)基本界面布局》构架了样式,本文实现记录轨迹的功能。

响应点击事件

vue中事件响应比较简单,代码如下:

5078f4df133166233bcb27b60e197f3d.png

图中红框中的表示响应click事件,代码响应如下

/**

* 开始记录按钮响应

*/

startLog() {

if (this.status === 0) {

this.logBtnText = '记录中..(点击停止)';

this.cssStart = 'red';

this.status = 1;

this.onStartLoc();

} else {

this.confirmObj.text = '是不是误触了?真的要停止记录?';

this.confirmObj.btnOk = '停止记录';

this.confirmObj.btnNo = '点错了';

this.confirmObj.title = '温馨提示';

this.confirmObj.okEvt = () => {

this.logBtnText = '开始记录';

this.cssStart = 'green';

this.status = 0;

this.confirmObj.show = false;

this.onEndLoc();

};

this.confirmObj.show = true;

}

},

这里表示在点击记录的时候,按钮变红,同时调用 onStartLoc 函数(代码如下)开始调用定位位置并记录位置。如果再次点击,就调用onEndLoc停止定位。

/**

* 打开数据库同时开始定位

*/

onStartLoc() {

const request = window.indexedDB.open('myLocation', '1');

request.onsuccess = (openData) => {

this.db = openData.target.result;

this.onGeoNow();

this.posObj.watchid = setInterval(this.onGeoNow, this.interVal * 1000);

};

request.onupgradeneeded = (upData) => {

this.db = upData.target.result;

if (!this.db.objectStoreNames.contains('locations')) {

this.db.createObjectStore('locations', {

autoIncrement: true,

});

}

};

},

onStartLoc函数中创建了IndexedDB的数据库和用于记录位置的表locations(参考《IndexedDB使用精简入门上篇》),同时调用onGeoNow函数开始获取地理位置(参考:关于HTML5中的定位函数)。注意: 这里使用的是setInterVal函数循环调用getCurrentPosition函数,为什么不使用watchPosition函数,因为我希望手动去设置数据的采样间隔。onGeoNow函数的定义如下:

/**

* 封装定位函数

*/

onGeoNow() {

navigator.geolocation.getCurrentPosition(

this.onLocSuc, this.onLocErr, this.posObj.options

);

},

/**

* 定位成功回调

*/

onLocSuc(position) {

const coord = {

time: position.timestamp,

latitude: position.coords.latitude,

longitude: position.coords.longitude,

accuracy: position.coords.accuracy,

heading: position.coords.heading,

speed: position.coords.speed,

};

const store = this.db.transaction(['locations'], 'readwrite').objectStore('locations');

store.add(coord);

this.consoleInfo += ` ${coord.time}`;

},

/**

* 定位失败回调

*/

onLocErr(err) {

console.log(err);

},

可以看到在定位成功获取到地理位置之后,将其数据信息写入了IndexedDB,也就是上面的store.add方法。最后是停止定位的响应函数:

/**

* 结束定位函数

*/

onEndLoc() {

clearInterval(this.posObj.watchid);

},

这里需要将setInterval的返回值的清除,调用clearInterval函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值