Vue+Openlayers实现在地图上绘制多边形Polygon,坐标数组三层赋值,否则不显示


场景

Vue+Openlayers实现地图上绘制线:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/121252960

上面实现添加点和线,怎么实现添加面/多边形Polygon

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

1、引入所需模块

//导入基本模块
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import { Fill,Style,Stroke} from "ol/style";
//导入相关模块
import { Tile as TileLayer , Vector as VectorLayer } from 'ol/layer'
import { TileWMS ,Vector as VectorSource } from 'ol/source'
import { Polygon} from "ol/geom";
import Feature from "ol/Feature";

2、声明多边形图层与数据源

  data() {
    return {
      map: null, // map地图
      layer:null, //地图图层
      polygonLayer: null,
      polygonSource: null,
   };
  },

3、封装绘制Polygon的方法

    //画多边形
    drawPolygon(data){ 
        debugger
        let self = this;
        //下边来添加一线feature
        var feature = new Feature({
            type: "Polygon",
            geometry: new Polygon(
                data  // 线的坐标
            ),
        });
        let lineStyle = new Style({
            fill: new Fill({
                color: 'rgba(1, 210, 241, 0.2)'
            }),
            stroke: new Stroke({
                color: 'rgba(255, 0, 0)',
                width: 4,
            }),
        });
        // 添加线的样式
        feature.setStyle(lineStyle);
        // 添加线的fature
        self.polygonSource.addFeature(feature);
    },

4、页面加载之后初始化地图并调用绘制多边形的方法

  mounted() {
    this.initMap();
    let pointArr = [[[[986957.12],[215578.12]],[[989763.12],[213860.12]],[[987415.12],[212008.12]],[[986957.12],[215578.12]]]];
    this.drawPolygon(pointArr);
  },

5、完整示例代码





6、注意事项

一开始不显示多边形也不报错,原始是坐标数组赋值时是嵌套的三层数组

let pointArr = [[[[986957.12],[215578.12]],[[989763.12],[213860.12]],[[987415.12],[212008.12]],[[986957.12],[215578.12]]]];

这里是三角形,需要四个点,且第一个点与第四个点坐标一致。

在使用Draw进行页面上绘制多边形时,绘制结束后可以看到其点位坐标也是如下三层数组的结构。