1. 问题描述
在使用openlayers开发时,遇到过交互绘制、编辑要素,有时还需要以geojson格式存储要素,今天就基于Vue写一个demo简单粗暴地记录一下这三个功能实现。各位有需要的GISer可以借鉴,如有指正和建议欢迎给评论哦~~
2.代码实现
<template>
<!-- 绘制、编辑、输出GeoJson数据 -->
<div id="map" style="width:100%;height:100%">
<div class="btns">
<button @click="drawFeature">绘制</button>
<button @click="editorFeature" v-text="editorBtnText"></button>
<button @click="outputJson">输出Json</button>
</div>
</div>
</template>
<script>
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import { Vector as VectorSource, OSM } from "ol/source";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { GeoJSON } from "ol/format";
import { Draw, Modify, Select } from "ol/interaction";
export default {
data() {
return {
map: null,
vectorLayer: null,
vectorSource: null,
draw: null,
select: null,
modify: null,
editorBtnText: "编辑"
};
},
mounted() {
// 底图
var baseLayer = new TileLayer({
source: new OSM()
});
// 矢量图层源
this.vectorSource = new VectorSource({
wrapX: false
});
// 矢量图层
this.vectorLayer = new VectorLayer({
source: this.vectorSource
});
this.map = new Map({
layers: [baseLayer, this.vectorLayer],
target: "map",
view: new View({
projection: "EPSG:4326",
center: [104.06531800244139, 30.65852484539117],
zoom: 10
})
});
},
methods: {
drawFeature() {
this.draw = new Draw({
source: this.vectorSource,
type: "Polygon"
});
this.map.addInteraction(this.draw);
// 绘制完成
this.draw.on("drawend", e => {
this.map.removeInteraction(this.draw);
this.draw = null;
});
},
editorFeature() {
if (this.editorBtnText == "编辑") {
this.editorBtnText = "完成编辑";
// 要素选择组件
this.select = new Select({
wrapX: false
});
// 要素编辑
this.modify = new Modify({
features: this.select.getFeatures()
});
// 编辑完成后
this.modify.on("modifyend", function(e) {
console.log("编辑后的要素:", e.features);
});
this.map.addInteraction(this.select);
this.map.addInteraction(this.modify);
} else {
this.editorBtnText = "编辑";
this.map.removeInteraction(this.select);
this.map.removeInteraction(this.modify);
this.select = null;
this.modify = null;
}
},
// 输出矢量图层要素为GeoJson数据
outputJson() {
let features = this.vectorSource.getFeatures();
let jsonObj = new GeoJSON().writeFeatures(features);
console.log("->GeoJson格式数据:", jsonObj);
}
}
};
</script>
<style scoped>
#map {
width: 100%;
height: 100%;
position: relative;
}
.btns {
position: absolute;
z-index: 999;
left: 50%;
top: 20px;
transform: translate(-50%);
}
.btns button {
display: inline-block;
text-decoration: none;
text-align: center;
height: 30px;
width: 90px;
}
</style>