123.在 Vue3 中使用 OpenLayers 实现绘制 Draw 多边形并 Modify 编辑图形

🎯 作者:彭麒
📮 邮箱:1062470959@qq.com
📌 声明:本篇博客仅用于技术学习与交流,若转载请注明出处。


一、效果预览

📍地图支持缩放、拖拽,绘制后可自由编辑已画图形。


二、前言

在 GIS 开发中,绘制图形并进行修改是非常常见的基础能力。无论是测量面积、标记区域、还是画草图,用户都需要在地图上自由绘制图形并进行后续的编辑操作。

本文将使用 Vue 3 + OpenLayers 6+ 实现如下功能:

✅ 在地图上绘制多边形
✅ 支持图形绘制的开始/结束
✅ 支持图形的修改与取消修改
✅ 使用 Vue 3 Composition API 编写,结构清晰,利于维护


三、技术栈

  • Vue 3 + Co

实现类似ArcGIS绘图工具条的自定义绘图控件,可以借助Vue.js和OpenLayers库来完成。 首先,在Vue.js中创建一个组件,用于包含OpenLayers地图。然后,使用OpenLayers的绘图工具来实现绘图功能。可以创建一个工具条组件,在该组件中包含各种绘图工具,比如点、线、面等。 下面是一个简单的实现示例: ``` html <template> <div class="map"> <div id="map" class="map-container"></div> <div class="toolbar"> <button @click="activateDraw(&#39;Point&#39;)">绘制点</button> <button @click="activateDraw(&#39;LineString&#39;)">绘制线</button> <button @click="activateDraw(&#39;Polygon&#39;)">绘制多边形</button> </div> </div> </template> <script> import &#39;ol/ol.css&#39; import { Map, View } from &#39;ol&#39; import { Tile as TileLayer, Vector as VectorLayer } from &#39;ol/layer&#39; import { OSM, Vector as VectorSource } from &#39;ol/source&#39; import { Draw, Modify, Snap } from &#39;ol/interaction&#39; export default { name: &#39;MapComponent&#39;, data() { return { map: null, draw: null, modify: null, snap: null } }, mounted() { this.initMap() }, methods: { initMap() { this.map = new Map({ target: &#39;map&#39;, layers: [ new TileLayer({ source: new OSM() }), new VectorLayer({ source: new VectorSource() }) ], view: new View({ center: [0, 0], zoom: 2 }) }) this.initDraw() }, initDraw() { const source = this.map.getLayers().item(1).getSource() this.draw = new Draw({ source: source, type: &#39;Point&#39; }) this.modify = new Modify({ source: source }) this.snap = new Snap({ source: source }) this.map.addInteraction(this.draw) this.map.addInteraction(this.modify) this.map.addInteraction(this.snap) this.draw.on(&#39;drawend&#39;, (event) => { const feature = event.feature feature.setId(new Date().getTime()) }) }, activateDraw(type) { this.draw.setActive(true) this.draw.setType(type) this.modify.setActive(true) this.snap.setActive(true) } } } </script> <style scoped> .map { position: relative; height: 400px; } .map-container { height: 100%; width: 100%; } .toolbar { position: absolute; top: 10px; left: 10px; z-index: 1; } </style> ``` 上面的代码中,首先初始化了一个OpenLayers地图,在地图上添加了OSM图层和一个空白的矢量图层,用于存储绘制的要素。然后,使用DrawModify和Snap三个交互对象来实现绘图功能。在initDraw方法中初始化这些交互对象,在activateDraw方法中根据用户选择的绘图类型来设置Draw交互对象的type属性。 在模板中,使用三个按钮来触发activateDraw方法,分别对应绘制点、线和多边形。同时,使用CSS样式将绘图工具条定位到地图左上角。 这样就完成了一个简单的自定义绘图控件,类似于ArcGIS的绘图工具条。可以根据自己的需要进行二次开发,添加更多的绘图工具和样式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

吉檀迦俐

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

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

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

打赏作者

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

抵扣说明:

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

余额充值