当前位置: 首页 > news >正文

131.在 Vue3 中使用 OpenLayers 测量长度和面积,并支持 modifyend 动态更新数值

🎯 效果预览(先睹为快)

点击「测量长度」或「测量面积」按钮进行绘制,绘制结束后弹窗会显示长度或面积值。当你拖动修改节点后,弹窗中的数值也会实时更新。


🧭 前言

在 Web GIS 开发中,测量工具是非常常用的功能,比如长度、面积测量。OpenLayers 提供了 DrawModify 交互,可让我们实现用户自由绘制图形并修改它们。我们将通过 Vue3 + OpenLayers 实现:

  • 支持用户测量长度(LineString)面积(Polygon)

  • 支持在图形修改后自动更新数值

  • 使用弹窗展示测量结果;

  • 实现简洁、可控的交互逻辑。


📦 项目环境

如你尚未安装 OpenLayers,可使用:

npm install ol

🧱 完整代码

<!--* @Author: 彭麒* @Date: 2025/5/28* @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测量长度和面积,modifyend后更改数值</div></div><h4><el-button type="danger" size="small" @click="measure('LineString')">测量长度</el-button><el-button type="danger" 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 Tile 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 Modify from 'ol/interaction/Modify'
import Overlay from 'ol/Overlay'
import { LineString, Polygon } from 'ol/geom'
import { getArea, getLength } 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'// 响应式状态
const map = ref(null)
const isMeasure = ref(true)
const measure_draw = ref(null)
const modify = ref(null)
const measureSource = new VectorSource({ wrapX: false })
let measureOverlayer = nullfunction clearMeasure() {measureSource.clear()isMeasure.value = false
}function measure(type) {isMeasure.value = falsemeasureSource.clear()if (measure_draw.value) {map.value.removeInteraction(measure_draw.value)}const draw = new Draw({source: measureSource,type,})measure_draw.value = drawmap.value.addInteraction(draw)let listenerlet sketchdraw.on('drawstart', (evt) => {isMeasure.value = truesketch = evt.featurelistener = sketch.getGeometry().on('change', (e) => {showMeasureInfo(e.target)})})draw.on('drawend', () => {sketch = nullunByKey(listener)map.value.removeInteraction(draw)})startModify()
}function startModify() {const modifyInteraction = new Modify({ source: measureSource })modify.value = modifyInteractionmap.value.addInteraction(modifyInteraction)modifyInteraction.on('modifyend', (e) => {const feature = e.features.getArray()[0]const geom = feature.getGeometry()showMeasureInfo(geom)})
}function showMeasureInfo(geom) {const measureBox = document.getElementById('measureBox')const measureInfo = document.getElementById('measureInfo')if (!measureOverlayer) {measureOverlayer = new Overlay({name: 'overlayLayer',element: measureBox,autoPan: true,autoPanAnimation: {duration: 250,},})map.value.addOverlay(measureOverlayer)}let output = ''let coordif (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 = outputmeasureOverlayer.setPosition(coord)
}function initMap() {const raster = new Tile({ source: new OSM() })const measureLayer = new VectorLayer({source: measureSource,style: new Style({fill: new Fill({ color: [0, 0, 0, 0.000005] }),stroke: new Stroke({ color: '#f00', width: 2 }),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: #f00;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>

📌 技术要点总结

  • 使用 Draw 交互进行绘制,结合 getLengthgetArea 实现测量;

  • 使用 Overlay 创建测量提示框;

  • 监听 Modifymodifyend 事件,动态更新信息;

  • 使用 unByKey 销毁绘制时绑定的事件,防止内存泄漏;

  • 使用 Vue3 refonMounted 实现响应式地图组件。


📚 参考资料

  • OpenLayers 官方文档

  • OpenLayers 测量示例

  • Vue3 官方文档


📝 最后

该功能是 GIS 系统中非常典型的交互组件,既可用于 Web 地图应用、三维测绘系统,也适合教学或私有项目使用。你可以将其封装为组件,以便更广泛复用。

欢迎点赞、评论、收藏,有问题欢迎一起探讨!🚀

http://www.xdnf.cn/news/691273.html

相关文章:

  • 不打架的协议互通,modbus转profibus网关的总线的高效互通方案
  • C53-字符串引入和注意事项.
  • JavaScript 中 this 指向全解析:从基础到 Vue 应用
  • 【加密算法】
  • Qt/C++开发监控GB28181系统/sip协议/同时支持udp和tcp模式/底层协议解析
  • 【Microsoft 365可用】PPT一键取消所有超链接
  • Python 进阶【二】:多进程编程
  • TCP三次握手/四次握手-TCP/IP四层模型-SSL/TLS-HTTP-HTTPS
  • Bootstrap法进行随机模拟
  • 第11章:工程组织与系列总结
  • 8086 处理器寄存器超详细解析:从原理到实战
  • 三分钟打通Stable Diffusion提示词(附实战手册)
  • TDengine 运维——用户和权限
  • Agent 的7 中设计模式
  • 4.Consul服务注册与发现
  • 【深度学习】10. 深度推理(含链式法则详解)RNN, LSTM, GRU,VQA
  • 33.第二阶段x64游戏实战-InLineHook
  • Jmeter——JDBC连接数据库相关
  • 【vscode】切换英文字母大小写快捷键如何配置
  • 《Google I/O 2025:AI浪潮下的科技革新风暴》
  • 宁夏农业科技:创新引领,赋能现代农业新篇章
  • c语言实现Linux命令行补全机制
  • 运用集合知识做斗地主案例
  • 智能指针的使用及原理
  • MCP 登场:掘金开启 AI 前端项目部署新时代
  • 第三章、数据链路层
  • C++智能指针用法及内存管理
  • 双因子COX 交互 共线性 -spss
  • 多态 向上转型
  • YOLO人体姿态估计Pytorch推理ONNX模型推理