You need to enable JavaScript to run this app. 如何在OpenLayers 3中实现多边形各边的长度标注功能
优惠活动
大模型
产品
解决方案
定价
更多

如何在OpenLayers 3中实现多边形各边的长度标注功能

OpenLayers 3 多边形边长按线段标注实现方案

核心逻辑和原OpenLayers 2版本的实现思路完全对齐,无需额外依赖,直接调用OpenLayers 3原生API即可实现所有线段长度标注效果,核心实现代码如下:

// 初始化底图与地图容器
const map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  view: new ol.View({
    center: ol.proj.fromLonLat([116.397, 39.908]),
    zoom: 13
  })
});

// 新建存储边长标注的矢量图层
const measureLabelLayer = new ol.layer.Vector({
  source: new ol.source.Vector(),
  zIndex: 10
});
map.addLayer(measureLabelLayer);

// (可选)多边形绘制交互,也可直接对接已有多边形数据
const drawPolygonInteraction = new ol.interaction.Draw({
  type: 'Polygon',
  style: new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: '#2385bb',
      width: 2
    }),
    fill: new ol.style.Fill({
      color: 'rgba(35, 133, 187, 0.1)'
    })
  })
});
map.addInteraction(drawPolygonInteraction);

/**
 * 为单个多边形生成分段边长标注
 * @param {ol.geom.Polygon} polygon 目标多边形几何对象
 */
function generateSegmentLengthLabel(polygon) {
  // 清空已有标注,不需要可删除该行
  measureLabelLayer.getSource().clear();

  // 取多边形外环坐标,内环可按需遍历getLinearRings()返回的数组
  const ringCoords = polygon.getLinearRing(0).getCoordinates();

  // 遍历所有相邻顶点,生成长度标注
  for (let i = 0; i < ringCoords.length - 1; i++) {
    const startCoord = ringCoords[i];
    const endCoord = ringCoords[i + 1];

    // 计算当前线段球面长度,默认单位为米
    const line = new ol.geom.LineString([startCoord, endCoord]);
    const length = ol.sphere.getLength(line);

    // 格式化长度显示文本
    const labelText = length >= 1000 
      ? `${(length / 1000).toFixed(2)} km` 
      : `${Math.round(length)} m`;

    // 计算线段中点作为标注锚点
    const midCoord = [
      (startCoord[0] + endCoord[0]) / 2,
      (startCoord[1] + endCoord[1]) / 2
    ];

    // 生成标注要素添加到图层
    const labelFeature = new ol.Feature(new ol.geom.Point(midCoord));
    labelFeature.setStyle(new ol.style.Style({
      text: new ol.style.Text({
        text: labelText,
        font: '14px Microsoft Yahei, sans-serif',
        fill: new ol.style.Fill({ color: '#e63946' }),
        stroke: new ol.style.Stroke({ color: '#ffffff', width: 2 }),
        offsetY: -8
      })
    }));
    measureLabelLayer.getSource().addFeature(labelFeature);
  }
}

// 绘制完成后自动生成分段标注
drawPolygonInteraction.on('drawend', (e) => {
  generateSegmentLengthLabel(e.feature.getGeometry());
});

功能调整说明

  • 若需标注已有多边形,直接调用generateSegmentLengthLabel方法,传入目标多边形的ol.geom.Polygon实例即可
  • 若需要标注多边形内环的边长,遍历polygon.getLinearRings()返回的所有环对象执行相同逻辑即可
  • 标注的字体、颜色、位置偏移可通过修改ol.style.Text的配置参数调整
  • 长度计算默认使用WGS84球面距离,若使用平面投影坐标系可替换为line.getLength()直接获取平面长度

内容的提问来源于stack exchange,提问作者Nima

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 12:15:05