1、绘制-Draw
新建一个用来绘制要素的图层:
const vector = new VectorLayer({
source: new VectorSource(),
style: {
"fill-color": "rgba(255, 255, 255, 0.2)",
"stroke-color": "#ffcc33",
"stroke-width": 2,
"circle-radius": 7,
"circle-fill-color": "#ffcc33",
},
});
在图层中对多边形要素进行绘制:
let draw = new Draw({
source: vector.getSource(),
type: "Polygon",
});
map.addInteraction(draw);
效果:
备注:draw.setActivity(false)即可禁用要素绘的制功能
2、选择-Select
实现绘制完一个多边形之后禁用多边形绘制,并且开启选择器功能
let draw = new Draw({
//放置一个source(要素需要放到Source里)
source: vector.getSource(),
type: "Polygon",
});
draw.on("drawend", function () {
draw.setActive(false);
//只需要new一个Select实例,后面可以根据select.setActive进行启用和禁用要素选择器
if (!select) select = new Select();
map.addInteraction(select);
});
map.addInteraction(draw);
效果:
3、修改-Modify
绘制图形之后结束绘制并且开启编辑多边形功能:
//新增一个绘制图形的矢量图层
const vector = new VectorLayer({
source: new VectorSource({ useSpatialIndex: false }),
style: {
"fill-color": "rgba(255, 255, 255, 0.2)",
"stroke-color": "#ffcc33",
"stroke-width": 2,
"circle-radius": 7,
"circle-fill-color": "#ffcc33",
},
});
//新增一个绘制图形的交互组件
let draw = new Draw({
//放置一个source(要素需要放到Source里)
source: vector.getSource(),
//绘制多边形
type: "Polygon",
});
let collection = new Collection();
let modify = new Modify({
//集合里的要素是动态添加修改的,只需要放一次就好
features: collection,
});
//添加一个选择器
map.addInteraction(modify);
//一个图形绘制结束时的回调方法
draw.on("drawend", function (event) {
//绘制好一个图形之后禁用绘制功能
draw.setActive(false);
//把当前绘制的要素放到可以编辑修改的集合里
collection.push(event.feature);
});
//把绘制多边形交互实例放置到
map.addInteraction(draw);
//添加矢量图层到map上
map.addLayer(vector);
效果:
也可以从Select获取Features(Collection集合)放置到Modify的features属性上
let modify = new Modify({
//集合里的要素是动态添加修改的,只需要放一次就好
features: select.getFeatures(),
});