首页 / OpenLayers / API 文档
Polygon
先看结论
面几何体。由一个外环和若干内环(洞)组成,用于行政区、地块、范围圈选。
new ol.geom.Polygon(coordinates, layout)
构造参数
| 参数 | 说明 |
|---|---|
coordinates | 三层数组:[[[x, y], ...]],外层是环的数组 |
layout | 坐标维度,默认 'XY' |
ends | 环的结束索引,一般由解析器自动生成 |
注意数组层级:Point 是 [x, y],LineString 是 [[x, y], ...],
Polygon 还要再包一层。少一层会报 “coordinates must be an array of LinearRings”。
var polygon = new ol.geom.Polygon([[
ol.proj.fromLonLat([116.28, 39.98]),
ol.proj.fromLonLat([116.52, 39.98]),
ol.proj.fromLonLat([116.52, 39.84]),
ol.proj.fromLonLat([116.28, 39.84])
]]);
示例里没有重复首点。OpenLayers 会在需要时自动闭合, 但为了与 GeoJSON 规范一致,写数据时通常还是把首点再放到末尾。
常用方法
| 方法 | 说明 |
|---|---|
getCoordinates() | 取三层坐标数组 |
getLinearRing(i) | 取第 i 个环,0 为外环 |
getArea() | 平面面积,投影单位的平方 |
getInteriorPoint() | 取面内一点,适合放标注 |
transform(src, dst) | 原地转换投影 |
getExtent() | 外接矩形 |
intersectsCoordinate(c) | 判断坐标是否落在面内 |
内环表示洞
第二个及之后的环是洞。绘制时按“外环逆时针、内环顺时针”的约定, 部分渲染器和空间数据库依赖这个方向来判断包含关系:
var withHole = new ol.geom.Polygon([
[ /* 外环,逆时针 */
[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]
],
[ /* 内环,顺时针 */
[3, 3], [3, 7], [7, 7], [7, 3], [3, 3]
]
]);
面积要用球面公式
getArea() 是平面面积。墨卡托投影下面积放大倍数随纬度平方增长,
用它可以比较相对大小,但不能直接当亩数或平方公里上报。
ol.sphere.getArea 返回真实椭球面积:
var planar = polygon.getArea(); // 平面面积
var real = ol.sphere.getArea(polygon); // 平方米
console.log((real / 1e6).toFixed(2) + ' km²');
面内标注不要用顶点平均位置,凹多边形时平均值可能落在面外。
用 getInteriorPoint() 得到的点保证在面内部。
经纬志(2026)。《Polygon》。https://www.jingweizhi.com/openlayers/api/polygon.html(访问日期 2026-11-03)。