示例簡介
本文介紹使用組件map和API的MapContext+wx.getLocation來實現活動軌跡回放。
最終效果:
實現過程
1、文件index.wxml代碼如下,這一塊比較簡單,可自行查看分析;
2、文件index.js存放所有功能的邏輯代碼,相對比較復雜,主要分析幾個重點方法:
1)方法getDistance用于計算兩個坐標點之間的距離,參數為兩個坐標點的經緯度;
2)方法translateMarker使用translateMarker實現marker平移,為了實現多點之間連續(xù)平移,在內部嵌套方法translateMarker;
3)wx.getLocation用來獲取當前的坐標點。
Tips:
points中的“+-”0.01等,無特別意義,可以自己任意修改;實際情況可調用接口獲取軌跡數據;
duration = getDistance * 2中的2,無特別意義,可根據實際情況自行調整。
// 全屏地圖路線圖并動畫移動// polyline中的points可以獲取json用來繪制軌跡圖// 獲取應用實例const app = getApp()Page({ data: { markers: [], // 標記點集合 polyline: [], // 坐標點集合 satellite: true, // 是否開啟衛(wèi)星圖 i: 0 // 用于循環(huán) }, onReady: function() { this.mapCtx = wx.createMapContext(‘map’); // 創(chuàng)建 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才執(zhí)行 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) }})