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