130.在 Vue3 中使用 OpenLayers 实现测量长度和面积功能(带尾随数字与关闭按钮)

🌟 前言

在 Web GIS 或地图相关的项目中,测量功能是最基础却又必不可少的模块之一。今天我们就来一起动手,在 Vue 3 + OpenLayers 环境中实现一个完整的测量工具,包括:

  • ✅ 测量长度(LineString)

  • ✅ 测量面积(Polygon)

  • ✅ 鼠标绘制时实时显示测量结果(尾随数字)

  • ✅ 测量完成后展示关闭按钮

最终效果如下👇:


🧱 项目准备

1️⃣ 安装依赖

确保你的项目中已经安装了 OpenLayers:

npm install ol

我们使用的是 Vue 3 + Vite 的环境。如果你还没创建项目,可以使用如下命令:

npm create vite@latest my-map-app 
cd my-map-app 
npm install 
npm install ol element-plus

🔧 核心实现

下面是完整的组件源码,可以直接拷贝到 Vue 组件中使用(支持 Composition API)👇

🗂️ MeasureMap.vue

<!--
 * @Author: 彭麒
 * @Date: 2025/5/22
 * @Email: 1062470959@qq.com
 * @Description: 此源码版权归吉檀迦俐所有,可供学习和借鉴或商用。
 -->
<template>
  <div class="container">
    <div class="w-full flex justify-center flex-wrap">
      <div class="font-bold text-[24px]">在Vue3中使用OpenLayers测量长度和面积,尾随数字和关闭按钮</div>
    </div>
    <h4>
      <el-button type="primary" size="small" @click="measure('LineString')">测量长度</el-button>
      <el-button type="primary" size="small" @click="measure('Polygon')">测量面积</el-button>
    </h4>
    <div id="vue-openlayers"></div>
    <!-- 测量弹窗信息 -->
    <div id="measureBox" class="measure-popup" v-show="isMeasure">
      <div class="popup-closer" @click="clearMeasure"></div>
      <div id="measureInfo"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import 'ol/ol.css'
import { Map, View } from 'ol'
import TileLayer from 'ol/layer/Tile'
import OSM from 'ol/source/OSM'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import Draw from 'ol/interaction/Draw'
import Overlay from 'ol/Overlay'
import { LineString, Polygon } from 'ol/geom'
import { getLength, getArea } from 'ol/sphere'
import { unByKey } from 'ol/Observable'
import Style from 'ol/style/Style'
import Stroke from 'ol/style/Stroke'
import Fill from 'ol/style/Fill'
import CircleStyle from 'ol/style/Circle'

// refs
const map = ref(null)
const measureDraw = ref(null)
const measureOverlayer = ref(null)
const isMeasure = ref(false)

const measureSource = new VectorSource({ wrapX: false })

// 清除测量
function clearMeasure() {
  measureSource.clear()
  isMeasure.value = false
}

// 测量功能
function measure(type) {
  const measureBox = document.getElementById('measureBox')
  const measureInfo = document.getElementById('measureInfo')

  // 创建 overlay
  measureOverlayer.value = new Overlay({
    name: 'overlayLayer',
    element: measureBox,
    autoPan: true,
    autoPanAnimation: {
      duration: 250
    }
  })
  map.value.addOverlay(measureOverlayer.value)
  measureSource.clear()

  if (measureDraw.value) {
    map.value.removeInteraction(measureDraw.value)
  }

  measureDraw.value = new Draw({
    source: measureSource,
    type
  })
  map.value.addInteraction(measureDraw.value)

  let listener
  let sketch

  measureDraw.value.on('drawstart', evt => {
    isMeasure.value = true
    sketch = evt.feature
    listener = sketch.getGeometry().on('change', e => {
      const geom = e.target
      let output = ''
      let coord

      if (geom instanceof Polygon) {
        const area = getArea(geom)
        output = '≈' + (Math.round((area / 1000000) * 100) / 100) + 'km<sup>2</sup>'
        coord = geom.getInteriorPoint().getCoordinates()
      }

      if (geom instanceof LineString) {
        const length = getLength(geom)
        output = '≈' + (Math.round((length / 1000) * 100) / 100) + 'km'
        coord = geom.getLastCoordinate()
      }

      measureInfo.innerHTML = output
      measureOverlayer.value.setPosition(coord)
    })
  })

  measureDraw.value.on('drawend', () => {
    unByKey(listener)
    map.value.removeInteraction(measureDraw.value)
  })
}

// 初始化地图
function initMap() {
  const raster = new TileLayer({
    source: new OSM()
  })

  const measureLayer = new VectorLayer({
    source: measureSource,
    style: new Style({
      fill: new Fill({ color: [0, 0, 0, 0.000005] }),
      stroke: new Stroke({ width: 2, color: '#f0f' }),
      image: new CircleStyle({
        radius: 5,
        fill: new Fill({ color: '#ff0000' })
      })
    })
  })

  map.value = new Map({
    target: 'vue-openlayers',
    layers: [raster, measureLayer],
    view: new View({
      center: [-11000000, 4600000],
      zoom: 13
    })
  })
}

onMounted(() => {
  initMap()
})
</script>

<style scoped>
.container {
  width: 840px;
  height: 590px;
  margin: 50px auto;
  border: 1px solid #42B983;
}
#vue-openlayers {
  width: 800px;
  height: 420px;
  margin: 0 auto;
  border: 1px solid #42B983;
  position: relative;
}
.measure-popup {
  position: absolute;
  background-color: transparent;
  color: #f0f;
  padding: 5px 35px 5px 10px;
  bottom: 5px;
  left: -50px;
  font-size: 16px;
  border-radius: 4px;
}
.popup-closer {
  text-decoration: none;
  position: absolute;
  top: 4px;
  right: 8px;
  cursor: pointer;
}
.popup-closer:after {
  content: "✖";
}
</style>


💡 小贴士

  • 推荐使用 ref 代替 document.getElementById 访问 DOM,更贴合 Vue 3 哲学;

  • Overlay 如果重复添加建议手动移除旧的;

  • 可以封装为通用 composable(比如:useMeasure());

  • 如果你想进一步扩展功能(比如导出、回退、支持多段等),欢迎关注我后续文章!


🎯 总结

本篇文章我们用 Vue 3 + OpenLayers 打造了一个实用的测量功能模块。功能完整、样式友好,适用于大多数 GIS 项目和地图前端开发中,非常适合初学者上手实战。


📎 源码获取

🎁 如需源码或示例项目,欢迎留言或私信我获取~


🗨️ 欢迎交流

如果你喜欢这篇文章或者对 OpenLayers、Vue GIS 项目感兴趣,欢迎点赞 👍 + 收藏 ⭐ + 关注我!

有任何问题也欢迎在评论区留言,我们一起学习进步~ 🧑‍💻👩‍💻

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吉檀迦俐

你的鼓励奖是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值