OpenLayers如何获取手动绘制的GeoJson数据

1. 前言

因为目前市面上与OpenLayers相关的项目实在太少,大部分也是不会开源的项目,所以每次要找一些资源和教程总是很难。网上的相关资料不是官网的例子就是版本过低的代码。导致每次做一个新功能都得从头开始。这里开一个总结的文档集合。记录下使用OpenLayers6遇到的问题和解决方案。

2. 需求

最近在做一个智能选址的功能,有一个需求是需要在地图上绘制一个几何多边形后获取绘制形状的GeoJson数据传到后台。

3. 基本设置

因为最近做的全是vue相关项目,所以例子是都是在v-cli项目中运行。

4. 实现方式

4-1. 定义基本架构


先定义好加载地图的区域和开始绘制结束绘制的按钮

4-2. 引入需要的模块

// 导入需要的模块
import "ol/ol.css";
import Draw from "ol/interaction/Draw";
import Map from "ol/Map";
import View from "ol/View";
import { OSM, Vector as VectorSource } from "ol/source";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { Style, Fill, Stroke, Circle as CircleStyle } from "ol/style";
import GeoJSON from "ol/format/GeoJSON";

4-3. 初始化地图和设置对应的操作事件

export default {
  name: "Home",
  data() {
    return {
      mapData: null,
      DrawVar: null,
      vectorSource: null
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      // 定义source
      this.vectorSource = new VectorSource();

      // 定义基本的底图的layer
      let baseLayer = new TileLayer({
        source: new OSM()
      });

      // 定义绘制图形的图层
      let drawLayer = new VectorLayer({
        source: this.vectorSource,
        // 绘制后填充的颜色
        style: new Style({
          fill: new Fill({
            color: "rgba(255, 0, 0, 0.2)"
          }),
          stroke: new Stroke({
            color: "rgba(255, 0, 0, 1)",
            width: 2
          }),
          image: new CircleStyle({
            radius: 7,
            fill: new Fill({
              color: "rgba(255, 0, 0, 1)"
            })
          })
        })
      });

      // 设置地图的相关属性
      this.mapData = new Map({
        layers: [baseLayer, drawLayer],
        target: "map",
        view: new View({
          center: [-11000000, 4600000],
          zoom: 4
        })
      });
    },
    startDraw() {
      // 设置绘制的draw
      this.DrawVar = new Draw({
        source: this.vectorSource,
        type: "Polygon"
      });
      // 添加绘制
      this.mapData.addInteraction(this.DrawVar);

      // 监听绘制结束事件
      this.DrawVar.on("drawend", (evt) => {
        let featureGeoJson = JSON.parse(new GeoJSON().writeFeature(evt.feature));
        console.log(featureGeoJson);
        this.mapData.removeInteraction(this.DrawVar);
      });
    },
    endDraw() {
      this.mapData.removeInteraction(this.DrawVar);
    }
  }
};

代码解析

  1. 上述代码中定义了2个图层baseLayerdrawLayerbaseLayersource是加载的openlayersOSM图层源作为底图。而drawLayer是声明一个矢量图层源,并且在定义draw的时候必须把2者的source设置相同,这样把绘制完成后的feature加到drawLayer图层里。
  2. 监听绘制结束事件会传递一个evt对象,从这个对象中我们可以获取到当前绘制完成后的feature,然后通过new GeoJSON().writeFeature方法把获取到feature转成我们要的GeoJson数据。

效果入下图

  1. 绘制形状


    [图片上传中...(geojson.png-4571be-1611294407803-0)]
  2. 转换后的geojson


    geojson.png

最后,喜欢的话请点个赞呗❤️❤️。

你可能感兴趣的:(OpenLayers如何获取手动绘制的GeoJson数据)