美文网首页
Openlayers 实例-绘制图形

Openlayers 实例-绘制图形

作者: 写前端的大叔 | 来源:发表于2020-02-16 21:25 被阅读0次

    Openlayers常用的API了解的差不多了,就开始进入实战了,首先从绘制基本的图形开始,这里主要介绍一下绘制线多边形矩形正文形五角星,相关的代码来自于官网的例子,这里只是对其进行了总结,绘制后的效果如下所示:

    图形绘制.png

    实现方法

    1.创建画笔

    在使用绘制功能前,首先需要创建一个绘制的交互操作,可以称之为画笔。如下所示:

    this.draw = new ol.interaction.Draw({
                source:sourse,
                type:type,
                geometryFunction:geometryFunction
            })
    

    其中数据源为矢量数据源,type为绘制的类型,包括PointLineStringPolygonCircle等类型。

    2.设置样式

    如果不用默认的样式,可以图层的几何图形设置样式,如下所示:

    var style = new ol.style.Style({
                fill: new ol.style.Fill({//填充样式
                  color: 'rgba(255, 255, 255, 0.2)'
                }),
                stroke: new ol.style.Stroke({//边框样式
                  color: '#ffcc33',
                  width: 2,
                  lineCap:'square'
                }),
                image: new ol.style.Circle({//点样式使用一个圆
                  radius: 7,
                  fill: new ol.style.Fill({
                    color: '#ffcc33'
                  })
                })
              });
    this.vectorLayer.setStyle(style)
    

    实现完这两步后,就可以执行绘制的功能了,为了方便以后复用,特意封装在一个文件中,如下所示。

    //绘制工具
    class DrawUtil{
        constructor(map){
            this.map = map
            this.vectorLayer = LayerUtil.vectorLayer()
            map.addLayer(this.vectorLayer)
            this._initStyle()
            this._initControl()
        }
    
        //初始化样式
        _initStyle(){
            var style = new ol.style.Style({
                fill: new ol.style.Fill({//填充样式
                  color: 'rgba(255, 255, 255, 0.2)'
                }),
                stroke: new ol.style.Stroke({//边框样式
                  color: '#ffcc33',
                  width: 2,
                  lineCap:'square'
                }),
                image: new ol.style.Circle({//点样式使用一个圆
                  radius: 7,
                  fill: new ol.style.Fill({
                    color: '#ffcc33'
                  })
                })
              });
            this.setStyle(style)
        }
    
        //初始化控件
        _initControl(){
            var drawToolLayout = document.createElement('div')
            drawToolLayout.className = 'draw-tool-layout'
            var control = new ol.control.Control({element: drawToolLayout})
            this.map.addControl(control)
            var typeList = [
                {name:'点',type:'Point'},
                {name:'线',type:'LineString'},
                {name:'面',type:'Polygon'},
                {name:'圆',type:'Circle'},
                {name:'三角形',type:'Triangle'},
                {name:'矩形',type:'Box'},
                {name:'正方形',type:'Square'},
                {name:'五角星',type:'Star'},
                {name:'重置',type:'None'}
            ]
            var self = this;
            typeList.forEach(item =>{
                var button = document.createElement('button')
                button.innerHTML = item.name;
                button.onclick = function (event) {
                    self.drawGeometry(event,item.type)
                }
                drawToolLayout.appendChild(button)
            })
        }
    
        //设置样式
        setStyle(style){
            this.style = style
            this.vectorLayer.setStyle(style)
        }
    
        //绘制
        drawGeometry(event,type){
            event.stopPropagation()
            var sourse = this.vectorLayer.getSource(),
                geometryFunction
            if(this.draw){
                this.map.removeInteraction(this.draw)
                this.map.removeInteraction(this.modify)
                this.draw = null
                this.modify = null
            }
            if(type === 'None'){
                sourse.clear()
                return;
            }
    
            if(type === 'Box'){
                type = 'Circle'
                geometryFunction = ol.interaction.Draw.createBox()
            }else if(type === 'Square'){
                type = 'Circle'
                geometryFunction = ol.interaction.Draw.createRegularPolygon(4)
            }else if(type === 'Triangle'){
                type = 'Circle'
                geometryFunction = ol.interaction.Draw.createRegularPolygon(3)
            }else if(type === 'Star'){
                type = 'Circle'
                geometryFunction = this.createStar();
            }
            this.draw = new ol.interaction.Draw({
                source:sourse,
                type:type,
                geometryFunction:geometryFunction
            })
    
            this.modify = new ol.interaction.Select({
                source:sourse,
            })
            this.map.addInteraction(this.modify)
            this.map.addInteraction(this.draw)
        }
    
        createStar(){
            return function(coordinates, geometry) {
                var center = coordinates[0]
                var last = coordinates[1]
                var dx = center[0] - last[0]
                var dy = center[1] - last[1]
                var radius = Math.sqrt(dx * dx + dy * dy)
                var rotation = Math.atan2(dy, dx)
                var newCoordinates = []
                var numPoints = 12
                for (var i = 0; i < numPoints; ++i) {
                  var angle = rotation + i * 2 * Math.PI / numPoints
                  var fraction = i % 2 === 0 ? 1 : 0.5;
                  var offsetX = radius * fraction * Math.cos(angle)
                  var offsetY = radius * fraction * Math.sin(angle)
                  newCoordinates.push([center[0] + offsetX, center[1] + offsetY])
                }
                newCoordinates.push(newCoordinates[0].slice())
                if (!geometry) {
                  geometry = new ol.geom.Polygon([newCoordinates])
                } else {
                  geometry.setCoordinates([newCoordinates])
                }
                return geometry
            };
        }
    }
    

    相关的代码以后将统一更新在github上。
    个人博客

    相关文章

      网友评论

          本文标题:Openlayers 实例-绘制图形

          本文链接:https://www.haomeiwen.com/subject/shayfhtx.html