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; }
addMarker方法:
//添加div marker function addMarker(icon, lng, lat) { var latlng = new L.LatLng(lat, lng); var marker = new L.Marker(latlng, { icon: icon, pane: drawPane }); vectorsLayer.addLayer(marker); return marker; }
效果图: