首页 / OpenLayers / API 文档
LineString
先看结论
折线几何体。由两个以上顶点按顺序连接,用于道路、河流、测量线等线性要素。
new ol.geom.LineString(coordinates, layout)
构造参数
| 参数 | 说明 |
|---|---|
coordinates | 坐标数组的数组:[[x1, y1], [x2, y2], ...] |
layout | 坐标维度,默认 'XY' |
var route = new ol.geom.LineString([
ol.proj.fromLonLat([116.310, 39.905]),
ol.proj.fromLonLat([116.400, 39.915]),
ol.proj.fromLonLat([116.485, 39.908])
]);
每个顶点都要单独转换。常见错误是只转换首尾两点, 或者把经纬度数组直接塞进去,结果整条线落在错误位置。
常用方法
| 方法 | 说明 |
|---|---|
getCoordinates() | 取顶点数组 |
setCoordinates(c) | 整体替换顶点 |
appendCoordinate(c) | 末尾追加一个顶点 |
getLength() | 平面长度,直接按投影单位累加 |
getCoordinateAt(fraction) | 按比例取线上一点,0 到 1 |
getFlatCoordinates() | 取展平的一维坐标数组 |
transform(src, dst) | 原地转换投影 |
getExtent() | 外接矩形 |
simplify(tolerance) | 抽稀顶点,减少渲染开销 |
getLength 不是真实距离
getLength() 返回的是投影平面上的长度。
在 EPSG:3857 下,高纬度地区会被显著放大,
用它算出的里程偏大。要真实距离必须走球面公式:
var planar = route.getLength(); // 平面长度,米(偏大)
var real = ol.sphere.getLength(route); // 椭球面长度,米
console.log(planar.toFixed(0), real.toFixed(0));
北京纬度约 40 度,墨卡托的放大系数接近 1.3, 一条实际 10 公里的路,平面长度可能显示 13 公里左右。
沿线取点
getCoordinateAt 按累计长度比例取点,
可用于沿线布设标记、动画移动。它取的是投影平面上的位置,
短距离使用没有问题。
var markers = [];
for (var i = 0; i <= 10; i++) {
var coord = route.getCoordinateAt(i / 10);
markers.push(new ol.Feature({ geometry: new ol.geom.Point(coord) }));
}
闭合折线请用 ol.geom.Polygon 而不是首尾重合的 LineString。
首尾重合的线在填充、面积计算和拓扑判断上都会出问题。
经纬志(2026)。《LineString》。https://www.jingweizhi.com/openlayers/api/linestring.html(访问日期 2026-11-03)。