1. 程式人生 > 實用技巧 >leaflet 繪製 帶箭頭的線

leaflet 繪製 帶箭頭的線

箭頭不是畫的線段,是貼的圖示,再按方向旋轉一下。

程式碼:

//新增箭頭線
function addLineDirection(polylinePointArr, source, target) {
    var lineDirection = {};

    var polyline1 = L.polyline(polylinePointArr, { stroke: true, color: "#009922", opacity: 0.3, weight: 14, pane: drawPaneBelow });
    vectorsLayer.addLayer(polyline1);
    lineDirection.polyline1 
= polyline1; var polyline2 = L.polyline(polylinePointArr, { stroke: true, color: "#009922", weight: 8, opacity: 0.6, pane: drawPaneBelow }); vectorsLayer.addLayer(polyline2); lineDirection.polyline2 = polyline2; var distanceSum = 0; var count = 0; for (var i = 0; i < polylinePointArr.length - 1; i++) { point1
= polylinePointArr[i]; point2 = polylinePointArr[i + 1]; var angle = calcLineAngle(point1, point2); var distance = Math.pow(Math.pow(point2[1] - point1[1], 2) + Math.pow(point2[0] - point1[0], 2), 0.5); distanceSum += distance; var arrowCount = Math.floor(distanceSum / 0.01) - count; count
+= arrowCount; for (var j = 1; j <= arrowCount; j++) { var lng = point1[1] + (point2[1] - point1[1]) * ((j - 0.2) / arrowCount); var lat = point1[0] + (point2[0] - point1[0]) * ((j - 0.2) / arrowCount); var width = 14; var height = 14; var html = '<img src="images/arrow.png" style="width:' + width + 'px; height:' + width + 'px; transform:rotate(' + angle + 'deg) scale(0.6); " />'; var icon = L.divIcon({ html: html, className: 'draw-vectors-label', iconSize: [width, height], iconAnchor: [width / 2.0, height / 2.0] }); lineDirection.marker = addMarker(icon, lng, lat); lineDirection.source = source; lineDirection.target = target; lineDirectionArr.push(lineDirection); } } } //計算箭頭圖示角度 function calcLineAngle(point1, point2) { var h = point2[0] - point1[0]; var w = point2[1] - point1[1]; var angle = Math.atan(Math.abs(h) / Math.abs(w)) * 180 / Math.PI; if (w == 0) { if (h > 0) { return -90; } if (h < 0) { return 90; } } if (h == 0) { if (w > 0) { return 0; } if (w < 0) { return 180; } } if (h > 0) { if (w > 0) { return 0 - angle; } if (w < 0) { return angle - 180; } } if (h < 0) { if (w > 0) { return angle; } if (w < 0) { return 180 - angle; } } return 0; }
View Code

效果圖: