接前一篇《》,繪圖功能雖然實現了,但是僅僅開發到這裏,做Demo還行,如果要應用到項目中,
顯然是不太靈活,因此,將繪圖功能封裝到控件中,作爲工具,將更有利於我們來使用。
先來看下openlayers自帶的控件。
1、ol.control.Control類
openlayers中所有控件的基類,因此,我們自定義繪圖控件,以繼承該類。
2、需求
1)、一個工具條,包含指針、繪點、繪線、繪面、繪圓、繪矩形、清空繪製等按鈕;
2)、單擊各個繪圖按鈕將切換至對應的繪圖狀態;
2)、單擊指針按鈕切換爲非繪圖狀態;
3)、單擊清空繪製清理掉所有已繪製的圖形。
3、代碼實現
1)、繼承
ol.control.DrawControl = function(opt_options){
var opt_options = opt_options || {};
//定義按鈕
this.drawType = ['None', 'Point', 'LineString', 'Polygon', 'Circle', 'Box', 'Clear'];
var defaultControlClassName = 'ol-unselectable ol-control';
this.element = document.createElement('div');
this.element.className = defaultControlClassName + ' ' + 'drawtools';
var createchildElement = function(options){
var btn = document.createElement('button');
btn.className = options.class;
btn.id = options.id;
var tipLable = 'Draw ' + options.value;
btn.title = tipLable;
btn.type = options.type;
btn.value = options.value;
return btn;
};
this.drawType.forEach(element => {
var btn = createchildElement({
type: 'button',
class: 'drawBtn',
value: element,
id: 'ol-draw-' + element.toLocaleLowerCase()
})
btn.onclick = function(evt){
evt.preventDefault();
this.btnFouceChanged(evt);
var value = evt.target.getAttribute('value');
this.addInteraction(value);
}.bind(this);
this.element.appendChild(btn);
});
this.source_ = undefined;
this.overLay_ = undefined;
this.drawing_ = undefined;
ol.control.Control.call(this, {
element: this.element,
target: opt_options.target
})
}
2)屬性方法
主要這個方法,用於實現繪圖命令切換
ol.control.DrawControl.prototype.addInteraction = function(shapeType){
if(shapeType !== 'None'){
var geomFunc = undefined;
if(shapeType === 'Clear'){
this.source_.clear();
return;
}
if(shapeType === 'Box') {
shapeType = 'Circle';
geomFunc = ol.interaction.Draw.createBox();
}
this.drawing_ = new ol.interaction.Draw({
source: this.source_,
type: shapeType,
freehand: false, //按住shift可以跟蹤鼠標繪製
geometryFunction: geomFunc
});
this.getMap().addInteraction(this.drawing_);
}
}
3)按鈕樣式
接下來就是按鈕樣式了,單獨用一個css文件。
4、結果
點擊按鈕即可以進行繪圖操作。
控件及完整Demo下載:
openlayers繪圖控件
本文基於openlayers4進行開發測試,但同樣適應於openlayers5。