0
点赞
收藏
分享

微信扫一扫

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

松鼠树屋 2021-09-21 阅读 74

1. 前言

2. 需求

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

3. 基本设置

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

4. 实现方式

4-1. 定义基本架构

<template>
  <div class="draw_map">
    <div id="map"></div>
    <el-button
      type="primary"
      @click="startDraw"
    >开始绘制
    </el-button>
    <el-button
      type="primary"
      @click="endDraw"
    >结束绘制
    </el-button>
  </div>
</template>

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

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. 绘制形状


  2. 转换后的geojson


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

举报
0 条评论