OpenLayers 图形交互编辑
注:当前使用的是 ol 5.3.0 版本,天地图使用的key请到天地图官网申请,并替换为自己的key
图形要素包括属性信息和几何信息,在实际应用中,不仅需要修改样式信息,也需要修改图形几何信息。在OpenLayers中,一般采用鼠标交互方式修改图形坐标。在OpenLayers5中提供了ol.interaction.Modify交互式控件,可以结合选择要素控件ol.interaction.Select使用。
本节主要介绍加载图形交互编辑。
1. 添加编辑几何图形
创建点、线、面几何图形并添加到地图中。
//绘制的几何图形要素 const pointFeature = new ol.Feature(new ol.geom.Point([11881771, 4588300])); const lineFeature = new ol.Feature( new ol.geom.LineString([[11421771, 4288300], [12428781, 4288350]])); const polygonFeature = new ol.Feature( new ol.geom.Polygon([[[11421771, 4228300], [11421771, 3588300], [11521771, 3588300], [11528771, 3688300], [12421771, 3988300]]])); //实例化一个矢量图层Vector作为绘制层 const source = new ol.source.Vector({ features: [pointFeature, lineFeature, polygonFeature] }); const vector = new ol.layer.Vector({ source: source, style: new ol.style.Style({ fill: new ol.style.Fill({ color: 'rgba(255, 255, 255, 0.2)' }), stroke: new ol.style.Stroke({ color: '#ff0000', width: 2 }), image: new ol.style.Circle({ radius: 7, fill: new ol.style.Fill({ color: '#ff0000' }) }) }) }); //将绘制层添加到地图容器中 map.addLayer(vector);
2. 创建编辑控件
在Modify控件中实现以下三个方法。
- init:控件初始化
- setEvents:设置事件,为当前选择的控件添加激活变更事件,在其事件处理函数中返回当前选择要素集的第一要素。
- setActive:调用选择要素控件和交互式编辑控件setActive方法,控制控件是否激活。
//定义修改几何图形功能控件 const Modify = { init: function () { //初始化一个交互选择控件,并添加到地图容器中 this.select = new ol.interaction.Select(); map.addInteraction(this.select); //初始化一个交互编辑控件,并添加到地图容器中 this.modify = new ol.interaction.Modify({ //选中的要素 features: this.select.getFeatures() }); map.addInteraction(this.modify); //设置几何图形变更的处理 this.setEvents(); }, setEvents: function () { //选中的要素 const selectedFeatures = this.select.getFeatures(); //添加选中要素变更事件 this.select.on('change:active', function () { selectedFeatures.forEach(selectedFeatures.remove, selectedFeatures); }); }, setActive: function (active) { //激活选择要素控件 this.select.setActive(active); //激活修改要素控件 this.modify.setActive(active); } }; //初始化几何图形修改控件 Modify.init(); //激活几何图形修改控件; Modify.setActive(true);
3. 完整代码
其中libs文件夹下的包需要更换为自己下载的本地包或者引用在线资源。
图形交互编辑
免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们。