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; }
效果图:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义