示例简介
本文介绍使用组件map和API的MapContext+wx.getLocation来实现活动轨迹回放。
最终效果:
实现过程
1、文件index.wxml代码如下,这一块比较简单,可自行查看分析;
2、文件index.js存放所有功能的逻辑代码,相对比较复杂,主要分析几个重点方法:
1)方法getDistance用于计算两个坐标点之间的距离,参数为两个坐标点的经纬度;
2)方法translateMarker使用translateMarker实现marker平移,为了实现多点之间连续平移,在内部嵌套方法translateMarker;
3)wx.getLocation用来获取当前的坐标点。
Tips:
points中的“+-”0.01等,无特别意义,可以自己任意修改;实际情况可调用接口获取轨迹数据;
duration = getDistance * 2中的2,无特别意义,可根据实际情况自行调整。
// 全屏地图路线图并动画移动// polyline中的points可以获取json用来绘制轨迹图// 获取应用实例const app = getApp()Page({ data: { markers: [], // 标记点集合 polyline: [], // 坐标点集合 satellite: true, // 是否开启卫星图 i: 0 // 用于循环 }, onReady: function() { this.mapCtx = wx.createMapContext(‘map’); // 创建 map 上下文 MapContext 对象 }, onLoad: function() { let that = this; // 获取当前坐标 wx.getLocation({ type: ‘wgs84’, success: (res) => { // 坐标集合 let points = [{ longitude: res.longitude, latitude: res.latitude }, { longitude: res.longitude + 0.01, latitude: res.latitude + 0.01 }, { longitude: res.longitude – 0.01, latitude: res.latitude + 0.02 }, { longitude: res.longitude – 0.01, latitude: res.latitude + 0.01 }, { longitude: res.longitude, latitude: res.latitude }]; // 标记点集合 let markers = points; markers.map((value, index) => { markers[index].id = index + 1; }); this.setData({ polyline: [{ points: points, color: “#FF0000DD”, width: 2 }], markers: markers, latitude: res.latitude, longitude: res.longitude }) this.translateMarker(markers); } }) }, // 平移marker,带动画 translateMarker: function(markers) { let that = this; let markerId = markers[that.data.i].id; let destination = { longitude: markers[that.data.i + 1].longitude, latitude: markers[that.data.i + 1].latitude }; let getDistance = that.getDistance(markers[that.data.i].latitude, markers[that.data.i].longitude, markers[that.data.i + 1].latitude, markers[that.data.i + 1].longitude); let duration = getDistance * 2; // 根据距离计算平移的速度,看起来保持匀速 this.mapCtx.translateMarker({ markerId: markerId, destination: destination, autoRotate: true, rotate: 30, duration: duration, success(res) { that.setData({ i: that.data.i + 1 }); // 小于长度减1才执行 if (that.data.i < markers.length – 1) { that.translateMarker(markers); } }, fail(err) { console.log('fail', err) } }) }, // 计算两坐标点之间的距离 getDistance: function(lat1, lng1, lat2, lng2) { let rad1 = lat1 * Math.PI / 180.0; let rad2 = lat2 * Math.PI / 180.0; let a = rad1 – rad2; let b = lng1 * Math.PI / 180.0 – lng2 * Math.PI / 180.0; let r = 6378137; return (r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))).toFixed(0) }})