MapLibre@5.24中实现带方向箭头的线

📅 2026/7/1 8:08:21
MapLibre@5.24中实现带方向箭头的线
!DOCTYPE html html langzh-CN head meta charsetUTF-8 meta nameviewport contentwidthdevice-width, initial-scale1.0 titleMapLibre GL JS 线上方向箭头示例/title script srchttps://unpkg.com/maplibre-gl5.24.0/dist/maplibre-gl.js/script link hrefhttps://unpkg.com/maplibre-gl5.24.0/dist/maplibre-gl.css relstylesheet / style body { margin: 0; padding: 0; } #map { position: absolute; top: 0; bottom: 0; width: 100%; } /style /head body div idmap/div script // 1. 初始化地图 const map new maplibregl.Map({ container: map, style: https://demotiles.maplibre.org/style.json, center: [116.397428, 39.90923], // 北京中心点 zoom: 13 }); // 2. 模拟一段路线数据 const routeData { type: FeatureCollection, features: [ { type: Feature, properties: {}, geometry: { type: LineString, coordinates: [ [116.35, 39.91], [116.38, 39.915], [116.40, 39.89], [116.43, 39.905], [116.46, 39.89] ] } } ] }; map.on(load, () { // 示例 LineString 数据 const routeGeoJSON { type: Feature, geometry: { type: LineString, coordinates: [ [116.38, 39.89], [116.40, 39.90], [116.42, 39.91], [116.44, 39.905], ], }, }; map.addSource(route, { type: geojson, data: routeGeoJSON, }); // —— ① 画线 —— map.addLayer({ id: route-line, type: line, source: route, paint: { line-color: #ffffff, line-width: 2, }, layout: { line-cap: round, line-join: round, }, }); // —— ② 注册 SVG 箭头图标 —— // SVG 箭头尖朝右(→)宽高 24x24viewBox 要匹配 const svgArrow svg xmlnshttp://www.w3.org/2000/svg width24 height24 viewBox0 0 24 24 path dM4 12 L16 6 L16 10 L22 10 L22 14 L16 14 L16 18 Z fill#ffffff/ /svg; const img new Image(); img.onload () { // addImage 必须在 onload 回调里 map.addImage(dir-arrow, img); // —— ③ 添加 symbol 图层沿线放箭头 —— map.addLayer({ id: route-arrows, type: symbol, source: route, layout: { symbol-placement: line, // 关键沿线分布 symbol-spacing: 120, // 箭头间距(px)可调 icon-image: dir-arrow, icon-size: 0.8, // icon-rotate: 90, // SVG 尖朝右→需转90°才顺线方向若尖朝上则删掉这行 icon-rotation-alignment: map, // 跟随地图旋转跟随线方向 icon-allow-overlap: true, icon-ignore-placement: true, }, paint: { icon-opacity: 0.9, }, }); }; img.src data:image/svgxml;charsetutf-8, encodeURIComponent(svgArrow); }); /script /body /html