携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第15天,点击查看活动详情
本文接着上一篇文章map地图实例-运动轨迹(一)继续来看如何实现运动轨迹的回放。map的api提供了translateMarker方法,可以平移marker,并且带动画效果
轨迹运动
创建map上下文MapContent对象
onLoad: function (options) {
this.mapCtx = wx.createMapContext('mymap');
this.trackPlay();
},
开始轨迹运动
MapContext.translateMarker,平移marker,带动画,setData的第2个参数相当于回调,待值设置成功之后再进行的方法。
trackPlay: function () {
const that = this;
const points = this.data.polylineSettings[0].points;
that.setData({
'markers[0].latitude': points[0].latitude,
'markers[0].longitude': points[0].longitude,
mapCenter: points[0],
}, function () {
that.mapCtx.translateMarker({
markerId: 1,// 要移动的marker的id
autoRotate: true,// 移动过程中是否自动旋转 marker
moveWithRotate: true,// 平移和旋转同时进行
duration: 1000,// 动画持续时长,默认1000
destination: points[0], // 指定 marker 要移动到的目标点的经纬度
})
that.beginTrack() // 轨迹回放
})
},
轨迹回放
用setInterval设置轨迹运动的时长,
beginTrack: function () {
const that = this;
let index = that.data.playIndex === 0 ? 0 : that.data.playIndex;
let points = this.data.polylineSettings[0].points;
let duration = that.data.duration;
that.data.trackTimer = setInterval(function () {
const point = points[index];
that.data.lastPoint = point;
that.mapCtx.translateMarker({
markerId: 1,
autoRotate: false,
moveWithRotate: true,
duration: duration,
destination: point,
rotate: point.gpsBearing,
fail: function (res) {
console.log(res);
},
success: function () {
that.setData({
playIndex: index,
showMessage: point.latitude + "," + point.longitude + "," + point.gpsBearing + "," + points.length + "," + index
})
that.mapCtx.getRegion({// 获取当前地图的视野范围
success: function (e) {// 不断修正中心点
if (that.checkOutRegion(point, e.southwest, e.northeast)) {
that.setData({
mapCenter: point,
})
}
}
});
if (index + 1 >= points.length) {
that.stopTrack()
}
index++;
}
})
}, duration);
},
结束回放
到达终点之后,结束回放,清除定时钟
stopTrack: function () { //结束回放
const that = this;
let points = this.data.polylineSettings[0].points;
that.setData({
playIndex: 0,
'markers[0].latitude': points[0].latitude,
'markers[0].longitude': points[0].longitude,
});
clearInterval(that.data.trackTimer);
},
缩放视野
缩放视野以展示当前轨迹运动到的地方
checkOutRegion: function (point, southwest, northeast) {
if (point.longitude < southwest.longitude || point.latitude < southwest.latitude) {
return true;
}
if (point.longitude > northeast.longitude || point.latitude > northeast.latitude) {
return true;
}
return false;
},
暂停回放
trackerPause: function () {
if (!this.data.isPause) {
clearInterval(this.data.trackTimer);
this.setData({
isPause: true
});
}
},
回放继续
trackerPlay: function () {
if (this.data.isPause) {
this.beginTrack();
this.setData({
isPause: false
});
}
},