---
title: 多段线
source: https://vjmap.com/guide/polyline.html
---

# 多段线
## 用法

```js
let data = {
    "type": "FeatureCollection",
    "features": [
        {
            "id": "1",
            "type": "Feature",
            "properties": {
                "name": "polyline1",
                "color": "#00ffff"
            },
            "geometry": {
                "coordinates": [
                    [
                        3006.0952985307595,
                        15198.972934052355
                    ],
                    [
                        12606.64046359223,
                        9285.59366571666
                    ],
                    [
                        4745.324495099878,
                        3720.060236694666
                    ],
                    [
                        3006.0952985307595,
                        15198.972934052355
                    ]
                ],
                "type": "LineString"
            }
        },
        {
            "id": "2",
            "type": "Feature",
            "properties": {
                "name": "polyline2",
                "color": "#ff00ff"
            },
            "geometry": {
                "coordinates": [
                    [
                        19841.833921319492,
                        13807.589576796912
                    ],
                    [
                        19841.833921319492,
                        4207.0444117340885
                    ],
                    [
                        26172.62819683108,
                        4207.0444117340885
                    ],
                    [
                        26172.62819683108,
                        13807.589576796912
                    ],
                    [
                        19841.833921319492,
                        13807.589576796912
                    ]
                ],
                "type": "LineString"
            }
        }
    ]
}
let polyline = new vjmap.Polyline({
    data: map.toLngLat(data), // CAD几何坐标转渲染经纬度
    // 如果是hover状态时，用红色，非hover状态时，取属性中的'color'做为颜色值
    lineColor: ['case', ['to-boolean', ['feature-state', 'hover']], 'red', ['get', 'color']],
    lineWidth: 3,
    isHoverPointer: true,
    isHoverFeatureState: true
});
polyline.addTo(map);
polyline.clickLayer(e => map.logInfo(`您点击了第 ${e.features[0].id} 个，名称为 ${e.features[0].properties.name}，颜色为 ${e.features[0].properties.color} `))
polyline.hoverPopup(f => `<h3>ID: ${f.properties.name}</h3>Color: ${f.properties.color}`, { anchor: 'bottom' });
```
<mapFrameEx>
<pre>
let svc = new vjmap.Service(env.serviceUrl, env.accessToken)
// 打开地图
let res = await svc.openMap({
    mapid: "sys_hello", // 地图ID
    mapopenway: vjmap.MapOpenWay.GeomRender, // 以几何数据渲染方式打开
    style: vjmap.openMapLightStyle() // div为深色背景颜色时，这里也传深色背景样式
})
if (res.error) {
    // 如果打开出错
    showError(res.error)
    return;
}
// 获取地图范围
let mapBounds = vjmap.GeoBounds.fromString(res.bounds);
// 根据地图范围建立几何投影坐标系
let prj = new vjmap.GeoProjection(mapBounds);
//
// 地图对象
let map = new vjmap.Map({
    container: 'map', // DIV容器ID
    style: svc.rasterStyle(), // 样式，这里是栅格样式
    center: prj.toLngLat(mapBounds.center()), // 设置地图中心点
    zoom: 1, // 设置地图缩放级别
    pitch: 0,
    renderWorldCopies: false // 不显示多屏地图
});
// 关联服务对象和投影对象
map.attach(svc, prj);
await map.onLoad();
let data = {
    "type": "FeatureCollection",
    "features": [
        {
            "id": "1",
            "type": "Feature",
            "properties": {
                "name": "polyline1",
                "color": "#00ffff"
            },
            "geometry": {
                "coordinates": [
                    [
                        3006.0952985307595,
                        15198.972934052355
                    ],
                    [
                        12606.64046359223,
                        9285.59366571666
                    ],
                    [
                        4745.324495099878,
                        3720.060236694666
                    ],
                    [
                        3006.0952985307595,
                        15198.972934052355
                    ]
                ],
                "type": "LineString"
            }
        },
        {
            "id": "2",
            "type": "Feature",
            "properties": {
                "name": "polyline2",
                "color": "#ff00ff"
            },
            "geometry": {
                "coordinates": [
                    [
                        19841.833921319492,
                        13807.589576796912
                    ],
                    [
                        19841.833921319492,
                        4207.0444117340885
                    ],
                    [
                        26172.62819683108,
                        4207.0444117340885
                    ],
                    [
                        26172.62819683108,
                        13807.589576796912
                    ],
                    [
                        19841.833921319492,
                        13807.589576796912
                    ]
                ],
                "type": "LineString"
            }
        }
    ]
}
let polyline = new vjmap.Polyline({
    data: map.toLngLat(data), // CAD几何坐标转渲染经纬度
    // 如果是hover状态时，用红色，非hover状态时，取属性中的'color'做为颜色值
    lineColor: ['case', ['to-boolean', ['feature-state', 'hover']], 'red', ['get', 'color']],
    lineWidth: 3,
    isHoverPointer: true,
    isHoverFeatureState: true
});
polyline.addTo(map);
// 点击事件
polyline.clickLayer(e =&gt; map.logInfo(`您点击了第 ${e.features[0].id} 个，名称为 ${e.features[0].properties.name}，颜色为 ${e.features[0].properties.color} `))
// hover事件
polyline.hoverPopup(f =&gt; `&lt;h3&gt;ID: ${f.properties.name}&lt;/h3&gt;Color: ${f.properties.color}`, { anchor: 'bottom' });
</pre>
</mapFrameEx>
<br/>
<br/>



也可以用先单独创建数据源，再创建线图层的写法，如
```js
map.addSource("lines", {
    type: "geojson",
    data: data
});
map.addLayer({
    id: 'lineLayers',
    source: 'lines',
    type: 'line',
    "layout": {
        "line-cap": "square", //butt 尖头，round 圆头，square平头
        "line-join": "round" //bevel平拐，round 圆拐，miter棱拐
    },
    "paint": {
        "line-width": 3, //宽度
        "line-color": ['case', ['to-boolean', ['feature-state', 'hover']], 'red', ['get', 'color']] //颜色
    }
})
```

或 属性用驼峰式大小写，不用区分layout还是paint属性

```js
map.addGeoJSONSource("lines", data);
map.addLineLayer("route", "lines", {
    lineCap: "square", //butt 尖头，round 圆头，square平头
    lineJoin: "round", //bevel平拐，round 圆拐，miter棱拐
    lineWidth: 3, //宽度
    lineColor: ['case', ['to-boolean', ['feature-state', 'hover']], 'red', ['get', 'color']] //颜色
})
```

这种通过创建数据源和图层的写法，响应事件时，需要监听`地图的图层事件`进行处理

```js
map.on("click", layerId, e => {})
```

## 常用方法


修改数据用 `setData`
```js
polyline.setData(newDataJson);
```

获取图层ID、数据源ID
```js
// 获取图层ID
polyline.getLayerId()
// 获取数据源ID
polyline.getSourceId()
```


显示或隐藏
```js
// 显示
polyline.show()
// 隐藏
polyline.hide()
```

删除
```js
// 删除
polyline.remove()
```


## 相关示例

![image-20240928152216876](https://vjmap.com/blogimages/202409281522930.png)

[单个多段线](https://vjmap.com/demo/#/demo/map/overlay/polyline/00polylineingle)

[批量绘制不同类型的多段线](https://vjmap.com/demo/#/demo/map/overlay/polyline/01polylineManyType)

[路径动画](https://vjmap.com/demo/#/demo/map/overlay/polyline/polylineAnimate)

[渐变线](https://vjmap.com/demo/#/demo/map/overlay/polyline/polylineGradient)

[多段线线型设置](https://vjmap.com/demo/#/demo/map/overlay/polyline/polylineLinetype)

[线型填充图案动画](https://vjmap.com/demo/#/demo/map/overlay/polyline/polylinePattern)

[多段线转多边形](https://vjmap.com/demo/#/demo/map/overlay/polyline/polylinetoPolygon)

## 类型定义

```ts
/**
 * 创建多段线.
 *
 **/
export  class Polyline extends OverlayLayerBase {
    options: PolylineOptions;
    constructor(options: PolylineOptions);
    addTo(map: Map, beforeId?: string): void;
    /** 替换 GeoJSON 图层的当前数据。
     @param {GeoJSON} [data] GeoJSON object to set. If not provided, defaults to an empty FeatureCollection.
     */
    setData(data: PointGeoJsonInput | PointGeoJsonInput[] | GeoJsonGeomertry | GeoPointLike | any): void;
    setLineCap(value: DataDrivenPropertyValueSpecification<"butt" | "round" | "square">): this;
    getLineCap(): DataDrivenPropertyValueSpecification<"butt" | "round" | "square">;
    setLineJoin(value: DataDrivenPropertyValueSpecification<"bevel" | "round" | "miter">): this;
    getLineJoin(): DataDrivenPropertyValueSpecification<"bevel" | "round" | "miter">;
    setLineMiterMimit(value: PropertyValueSpecificationEx<number>): this;
    getLineMiterMimit(): PropertyValueSpecificationEx<number>;
    setLineRoundLimit(value: PropertyValueSpecificationEx<number>): this;
    getLineRoundLimit(): PropertyValueSpecificationEx<number>;
    setLineSortKey(value: DataDrivenPropertyValueSpecification<number>): this;
    getLineSortKey(): DataDrivenPropertyValueSpecification<number>;
    setLineOpacity(value: DataDrivenPropertyValueSpecification<number>): this;
    getLineOpacity(): DataDrivenPropertyValueSpecification<number>;
    setLineColor(value: DataDrivenPropertyValueSpecification<ColorSpecification>): this;
    getLineColor(): DataDrivenPropertyValueSpecification<ColorSpecification>;
    setLineTranslate(value: PropertyValueSpecificationEx<[number, number]>): this;
    getLineTranslate(): PropertyValueSpecificationEx<[number, number]>;
    setLineTranslateAnchor(value: PropertyValueSpecificationEx<"map" | "viewport">): this;
    getLineTranslateAnchor(): PropertyValueSpecificationEx<"map" | "viewport">;
    setLineWidth(value: DataDrivenPropertyValueSpecification<number>): this;
    getLineWidth(): DataDrivenPropertyValueSpecification<number>;
    setLineGapWidth(value: DataDrivenPropertyValueSpecification<number>): this;
    getLineGapWidth(): DataDrivenPropertyValueSpecification<number>;
    setLineOffset(value: DataDrivenPropertyValueSpecification<number>): this;
    getLineOffset(): DataDrivenPropertyValueSpecification<number>;
    setLineBlur(value: DataDrivenPropertyValueSpecification<number>): this;
    getLineBlur(): DataDrivenPropertyValueSpecification<number>;
    setLineDasharray(value: DataDrivenPropertyValueSpecification<number[]>): this;
    getLineDasharray(): DataDrivenPropertyValueSpecification<number[]>;
    setLinePattern(value: DataDrivenPropertyValueSpecification<ResolvedImageSpecification>): this;
    getLinePattern(): DataDrivenPropertyValueSpecification<ResolvedImageSpecification>;
    setLineGradient(value: ExpressionSpecificationEx): this;
    getLineGradient(): ExpressionSpecificationEx;
}



export  class OverlayLayerBase {
    sourceId?: string;
    layerId?: string;
    _map?: Map;
    constructor();
    addTo(map: Map, beforeId?: string): void;
    /**
     * 获取数据源ID
     * @return {string | undefined}
     */
    getSourceId(): string | undefined;
    /**
     * 获取图层ID
     * @return {string | undefined}
     */
    getLayerId(): string | undefined;
    /**
     * 获取数据源的数据
     * @return {GeoJsonGeomertry | undefined}
     */
    getData(): GeoJsonGeomertry | undefined;
    remove(): void;
    /** 每当鼠标悬停在这些图层上时，将地图的光标设置为“指针”。
     @returns A function to remove the handler.
     * @param layerOrLayers
     */
    hoverPointer(): void;
    /**
     每当将鼠标悬停在这些图层中的某个特征上时，更新连接源 [s] 中特征的特征状态。
     * @param enterCb
     * @param leaveCb
     */
    hoverFeatureState(enterCb?: (arg0: {}) => void, leaveCb?: (arg0: {}) => void): void;
    /** 将鼠标悬停在这些图层中的某个要素上时，会显示一个弹出窗口。
     @param htmlFunc Function that receives feature and popup, returns HTML.
     @param {Object<PopupOptions>} popupOptions Options passed to `Popup()` to customise popup.
     @example hoverPopup(f => `<h3>${f.properties.Name}</h3> ${f.properties.Description}`, { anchor: 'left' });
     */
    hoverPopup(htmlFunc: any, popupOptions?: PopupOptions): any;
    /** 每当单击这些图层中的要素时都会显示一个弹出窗口。
     @param htmlFunc Function that receives feature and popup, returns HTML.
     @param {Object<PopupOptions>} popupOptions Options passed to `Popup()` to customise popup.

     @returns A function that removes the handler.
     @example clickPopup(f => `<h3>${f.properties.Name}</h3> ${f.properties.Description}`, { maxWidth: 500 });

     */
    clickPopup(htmlFunc: (arg0: {}) => void, popupOptions?: PopupOptions): any;
    /** 每当单击这些图层中的要素时都会触发回调。
     @param {function} cb Callback that receives event with .features property
     @returns A function that removes the handler.
     */
    clickLayer(cb: any): any;
    /** 当鼠标悬停在这些图层中的要素上时触发回调。
     @returns A function to remove the handler.
     */
    hoverLayer(cb: any): any;
    /**
     * 使给定的图层可见。
     * @param layer
     */
    show(): void;
    /**
     * 使给定的图层不可见。
     * @param layer
     */
    hide(): void;
    /** 根据参数使给定的图层隐藏或可见。
     @param {boolean} state True for visible, false for hidden.
     */
    toggle(state: boolean): boolean;
    /** 在一个或多个图层上设置绘制或布局属性。
     @example setProperty('fillOpacity', 0.5)
     */
    setProperty(prop: string | object, value?: any): void;
    /** 根据样式规范，获取给定图层 ID 的图层定义。
     */
    getLayerStyle(): LayerSpecification;
    /**
     * 设置图层样式
     * @param layer
     * @param style
     */
    setLayerStyle(style: any): void;
    /** 替换一个图层的过滤器。
     @param {Array} filter New filter to set.
     @example setFilter(['==','level','0']]);
     */
    setFilter(filter: FilterSpecification): void;
}

export  interface OverlayLayerBaseOptions {
    sourceId?: string;
    sourceLayer?: string;
    layerId?: string;
    minzoom?: number;
    maxzoom?: number;
    filter?: any;
    visibility?: "visible" | "none";
    isHoverPointer?: boolean;
    isHoverFeatureState?: boolean;
}



export  type LineLayerSpecification = {
    id: string;
    type: "line";
    metadata?: unknown;
    source: string;
    "source-layer"?: string;
    minzoom?: number;
    maxzoom?: number;
    filter?: FilterSpecification;
    layout?: {
        "line-cap"?: DataDrivenPropertyValueSpecification<"butt" | "round" | "square">;
        "line-join"?: DataDrivenPropertyValueSpecification<"bevel" | "round" | "miter">;
        "line-miter-limit"?: PropertyValueSpecificationEx<number>;
        "line-round-limit"?: PropertyValueSpecificationEx<number>;
        "line-sort-key"?: DataDrivenPropertyValueSpecification<number>;
        visibility?: "visible" | "none";
    };
    paint?: {
        "line-opacity"?: DataDrivenPropertyValueSpecification<number>;
        "line-color"?: DataDrivenPropertyValueSpecification<ColorSpecification>;
        "line-translate"?: PropertyValueSpecificationEx<[number, number]>;
        "line-translate-anchor"?: PropertyValueSpecificationEx<"map" | "viewport">;
        "line-width"?: DataDrivenPropertyValueSpecification<number>;
        "line-gap-width"?: DataDrivenPropertyValueSpecification<number>;
        "line-offset"?: DataDrivenPropertyValueSpecification<number>;
        "line-blur"?: DataDrivenPropertyValueSpecification<number>;
        "line-dasharray"?: DataDrivenPropertyValueSpecification<Array<number>>;
        "line-pattern"?: DataDrivenPropertyValueSpecification<ResolvedImageSpecification>;
        "line-gradient"?: ExpressionSpecificationEx;
    };
};

export  type LineLayerStyleProp = {
    metadata?: unknown;
    source?: string;
    sourceLayer?: string;
    minzoom?: number;
    maxzoom?: number;
    filter?: FilterSpecification;
    lineCap?: DataDrivenPropertyValueSpecification<"butt" | "round" | "square">;
    lineJoin?: DataDrivenPropertyValueSpecification<"bevel" | "round" | "miter">;
    lineMiterMimit?: PropertyValueSpecificationEx<number>;
    lineRoundLimit?: PropertyValueSpecificationEx<number>;
    lineSortKey?: DataDrivenPropertyValueSpecification<number>;
    visibility?: "visible" | "none";
    lineOpacity?: DataDrivenPropertyValueSpecification<number>;
    lineColor?: DataDrivenPropertyValueSpecification<ColorSpecification>;
    lineTranslate?: PropertyValueSpecificationEx<[number, number]>;
    lineTranslateAnchor?: PropertyValueSpecificationEx<"map" | "viewport">;
    lineWidth?: DataDrivenPropertyValueSpecification<number>;
    lineGapWidth?: DataDrivenPropertyValueSpecification<number>;
    lineOffset?: DataDrivenPropertyValueSpecification<number>;
    lineBlur?: DataDrivenPropertyValueSpecification<number>;
    lineDasharray?: DataDrivenPropertyValueSpecification<Array<number>>;
    linePattern?: DataDrivenPropertyValueSpecification<ResolvedImageSpecification>;
    lineGradient?: ExpressionSpecificationEx;
};
```