官网demo 地址:
Extent Interaction
在openlayers中可以使用ExtentInteraction添加交互事件,配合shiftKeyOnly实现按住shift键绘制边界区域。
const map = new Map({
layers: [
new TileLayer({
source: new OSM(),
}),
],
target: "map",
view: new View({
center: [0, 0],
zoom: 2,
}),
});
const extent = new ExtentInteraction({ condition: shiftKeyOnly });
map.addInteraction(extent);
按住shift绘制矩形,按住shift键点击图形删除。
监听extentchanged事件,记录绘制的矩形数据。
// 监听 extentchanged 事件,获取矩形选择范围
extent.on("extentchanged", (event) => {
this.extentData = event.extent;
});
getData() {
console.log("结果", this.extentData);
},
完整代码:
<template>
<div class="box">
<h1>Extent Interaction</h1>
<div id="map"></div>
<el-button type="primary" @click="getData">获取数据</el-button>
</div>
</template>
<script>
import ExtentInteraction from "ol/interaction/Extent.js";
import Map from "ol/Map.js";
import OSM from "ol/source/OSM.js";
import TileLayer from "ol/layer/Tile.js";
import View from "ol/View.js";
import { shiftKeyOnly } from "ol/events/condition.js";
export default {
name: "",
components: {},
data() {
return {
map: null,
extentData: "",
};
},
computed: {},
created() {},
mounted() {
const map = new Map({
layers: [
new TileLayer({
source: new OSM(),
}),
],
target: "map",
view: new View({
center: [0, 0],
zoom: 2,
}),
});
const extent = new ExtentInteraction({ condition: shiftKeyOnly });
map.addInteraction(extent);
// 监听 extentchanged 事件,获取矩形选择范围
extent.on("extentchanged", (event) => {
this.extentData = event.extent;
});
},
methods: {
getData() {
console.log("结果", this.extentData);
},
},
};
</script>
<style lang="scss" scoped>
#map {
width: 100%;
height: 500px;
}
.box {
height: 100%;
}
</style>