1.前言
在地图应用中,在线绘制图形也是必不可少的功能。无论实现标注、空间分析、编辑,都需要首先绘制图形。
2.实战
import Draw from 'ol/interaction/Draw.js';
引入Draw类。
//定义vector layer
const source = new VectorSource({wrapX: false});
const vector = new VectorLayer({
source: source,
});
map.addLayer(vector);
定义一个vector layer,加到map上。
/**
*处理下拉控件的onchagne事件。
*/
typeSelect.onchange = function () {
map.removeInteraction(draw);
addInteraction();
};
//定义绘制对象
let draw;
function addInteraction() {
const value = typeSelect.value;
if (value !== 'None') {
draw = new Draw({
source: source,
type: typeSelect.value,
style: styles[value],
});
map.addInteraction(draw);
}
}
在下拉框的onchange事件中触发删除上一个Interaction,添加一个新的Draw对象。
Draw的构造参数中:
source是一个vectorSource对象;
type的取值有: 'Point', 'LineString', 'LinearRing', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection','Circle'。
const styles = {
Point: {
'circle-radius': 5,
'circle-fill-color': 'red',
},
LineString: {
'circle-radius': 5,
'circle-fill-color': 'red',
'stroke-color': 'yellow',
'stroke-width': 2,
},
Polygon: {
'circle-radius': 5,
'circle-fill-color': 'red',
'stroke-color': 'yellow',
'stroke-width': 2,
'fill-color': 'blue',
},
Circle: {
'circle-radius': 5,
'circle-fill-color': 'red',
'stroke-color': 'blue',
'stroke-width': 2,
'fill-color': 'yellow',
},
};
styles定义了绘制图形时的样式。
document.getElementById('undo').addEventListener('click', function () {
draw.removeLastPoint();
});
为撤销按钮注册单击事件,调用draw对象的删除最后一个绘制的点(removeLastPoint)方法,也就是对于绘制线、多边形时、且在未进行双击结束绘制前是有效的,对于绘制圆形也是有效的。
效果如下: