百度地图折线 Polyline:颜色、虚线、方向箭头和纹理(JSAPI 4.0)

画线用 new BMap.Polyline(点数组, 样式) 再 map.addOverlay(polyline)。样式选项:strokeColor 颜色、strokeWeight 线宽、strokeOpacity 透明度、strokeStyle 实线 'solid' 或虚线 'dashed',dashArray 自定义虚线间隔;icons 配合 BMap.IconSequence 在线上重复画箭头或圆点;strokeTexture 用图片做线的纹理。map.setViewport([polyline]) 可以让视野正好容纳整条线。

基础折线

const path = [
  new BMap.Point(116.36, 39.93),
  new BMap.Point(116.40, 39.94),
  new BMap.Point(116.44, 39.93),
];

const polyline = new BMap.Polyline(path, {
  strokeColor: '#1890ff',
  strokeWeight: 4,
  strokeOpacity: 0.9,
});
map.addOverlay(polyline);
map.setViewport([polyline]); // 视野适配这条线

沿东交民巷的折线

在线示例:折线

运行中修改样式:setStrokeColor()、setStrokeWeight()、setStrokeOpacity()、setStrokeStyle();修改路径:setPath(points)、setPositionAt(index, point);读取路径:getPath()。

虚线

// 默认虚线
new BMap.Polyline(path, {strokeColor: '#f5222d', strokeWeight: 6, strokeStyle: 'dashed'});

// 自定义间隔:实线段 20px、空白 10px,端点圆角
new BMap.Polyline(path, {
  strokeColor: '#52c41a',
  strokeWeight: 6,
  strokeStyle: 'dashed',
  dashArray: [20, 10],
  strokeLineCap: 'round',
});

从上到下:实线、默认虚线、dashArray: [20, 10] 的虚线:

实线、默认虚线和自定义间隔虚线

方向箭头和沿线圆点

const arrow = new BMap.Symbol(BMap_Symbol_SHAPE_BACKWARD_OPEN_ARROW, {
  scale: 0.6,
  strokeColor: '#fff',
  strokeWeight: 2,
});

const polyline = new BMap.Polyline(path, {
  strokeColor: '#18a45b',
  strokeWeight: 8,
  strokeOpacity: 0.8,
  // IconSequence(符号, 起始偏移, 重复间隔)
  icons: [new BMap.IconSequence(arrow, '10', '30')],
});
map.addOverlay(polyline);

换成圆形符号就是沿线的站点圆点:

const dot = new BMap.Symbol(BMap_Symbol_SHAPE_CIRCLE, {
  scale: 5,
  fillColor: '#e74c3c',
  fillOpacity: 1,
  strokeWeight: 1,
});
new BMap.Polyline(points, {
  strokeColor: '#f0c040',
  icons: [new BMap.IconSequence(dot, '0', '20px', false)],
});

绿线上是白色方向箭头,黄线上是红色圆点:

折线上的方向箭头和圆点

在线示例:折线上添加方向箭头

纹理线

new BMap.Polyline(path, {
  strokeColor: '#28a745',
  strokeWeight: 8,
  strokeTexture: {
    url: 'https://mapopen-pub-jsapigl.bj.bcebos.com/svgmodel/Icon_road_green_arrow.png',
    width: 16,
    height: 64,
  },
});

纹理图片沿线方向重复平铺,适合做导航路线、管线等效果:

带箭头纹理的路线

在线示例:设置折线的纹理贴图

事件和计算

polyline.addEventListener('click', (e) => console.log('点击了线', e.point));

// 两点间距离(米)
map.getDistance(path[0], path[2]);

常见问题

线有几千个点会卡吗?

单条 Polyline 几千个点没问题。几百上千条线(例如全城公交线网)改用线图层 PolylineLayer。

线和道路对不上?

坐标系不一致。高德、腾讯的坐标是 GCJ02,需要设置 coordType: 'BMAP_COORD_GCJ02' 或全局 BMap.coordType = BMAP_COORD_GCJ02。

能做渐变色的线吗?

Polyline 只支持单色。渐变或按数据着色的线,用线图层 PolylineLayer 的数据驱动样式。

和旧写法的区别

旧教程画方向箭头的写法(IconSequence + Symbol)在 4.0 中一样可用。4.0 新增了 dashArray 自定义虚线、strokeTexture 纹理和 strokeLineCap / strokeLineJoin 端点样式,以前要靠多条线叠加或 Canvas 自绘才能实现的效果,现在一个选项就够了。

参考

posted @ 2026-12-05 09:13  map_3d_vis  阅读(4)  评论(0)    收藏  举报