高德地圖實現軌跡回放的方式之一:使用高德地圖官方api中UI組件庫中的軌跡展示。通過軌跡展示創建巡航器,實現軌跡回放。創建巡航器實現軌跡回放的好處就是回放速度隨時控制隨時變化,不好的瀏覽器必須支持canvas(IE8及以下不支持)。效果圖如下:
看主要的代碼
1 AMapUI.load(['ui/misc/PathSimplifier'], function (PathSimplifier) { 2 3 if (!PathSimplifier.supportCanvas) { 4 alert('當前環境不支持 Canvas!'); 5 return; 6 } 7 //回放路徑等配置項,參考官方api 8 var defaultRenderOptions = { 9 pathNavigatorStyle: { 10 width:16, 11 height:16, 12 autoRotate:true, 13 lineJoin:'round', 14 content:'defaultPathNavigtor', 15 fillStyle:'#087EC4', 16 strokeStyle:'#116394', 17 lineWidth:1, 18 pathLinePassedStyle: { 19 lineWidth:2, 20 strokeStyle:'rgba(0, 160, 220, 0.8)', 21 borderWidth:1, 22 borderStyle:'#eee', 23 dirArrowStyle:false 24 } 25 } 26 }; 27 28 var pathSimplifierIns = new PathSimplifier({ 29 zIndex: 100, 30 map: map, 31 getPath: function(pathData, pathIndex) { 32 return pathData.path; 33 }, 34 getHoverTitle: function(pathData, pathIndex, pointIndex) { 35 //返回鼠標懸停時顯示的信息 36 if (pointIndex >= 0) { 37 //鼠標懸停在某個軌跡節點上 38 return pathData.name + ',點:' + pointIndex + '/' + pathData.path.length; 39 } 40 //鼠標懸停在節點之間的連線上 41 return pathData.name + ',點數量' + pathData.path.length; 42 }, 43 renderOptions: defaultRenderOptions 44 }); 45 46 window.pathSimplifierIns = pathSimplifierIns; 47 //根據數據來繪制路線 48 pathSimplifierIns.setData([{ 49 name: '軌跡', 50 path: lineArr 51 }]); 52 //創建巡航器 53 var navg = pathSimplifierIns.createPathNavigator(0,{ 54 loop: true,//是否循環播放 55 speed: parseInt(speed.value),//回放速度控制,這里使用的是select下拉列表value值控制 56 pathNavigatorStyle: { 57 width:24, 58 height:24, 59 content: PathSimplifier.Render.Canvas.getImageContent('image/plane.png'),//自定義巡航器樣式 60 strokeStyle:null, 61 fillStyle:null 62 } 63 }); 64 //控制播放按鈕 65 start.onclick = function (){ 66 navg.start(); 67 } 68 69 pause.onclick = function (){ 70 navg.pause(); 71 72 alert('當前為止走過的距離'+parseInt(navg.getMovedDistance()/1000)+'KM,回放速度為:'+parseInt(navg.getSpeed())+'Km/h'); 73 74 } 75 76 resume.onclick = function (){ 77 navg.resume(); 78 79 } 80 stop.onclick = function (){ 81 navg.stop(); 82 83 } 84 85 86 //下拉列表value值改變速度改變 87 speed.onchange=function(){ 88 var spe = speed.value; 89 navg.setSpeed(spe); 90 91 }; 92 93 //起點終點標記 94 var startPot = lineArr[0]; 95 96 var endPot = lineArr[lineArr.length-1]; 97 98 var stmarker = new AMap.Marker({ 99 map: map, 100 position: [startPot[0], startPot[1]], //基點位置 101 icon: "https://webapi.amap.com/theme/v1.3/markers/n/start.png", 102 zIndex: 10 103 }); 104 var endmarker = new AMap.Marker({ 105 map: map, 106 position: [endPot[0], endPot[1]], //基點位置 107 icon: "https://webapi.amap.com/theme/v1.3/markers/n/end.png", 108 zIndex: 10 109 }); 110 111 });
以上就是高德地圖實現軌跡回放方法之一。此高德地圖UI組件需要在服務器環境下運行,詳細代碼地址github,僅作學習總結只用!