繪圖是webgis前端開發中很多見的一個需求,在openlayers中,包含一個ol.interaction.Draw類,提供交互式繪圖功能,用起來較爲方便。
1、ol.interaction.Draw類
ol.interaction.Draw是openlayers交互式操作中的繪圖操作類,支持繪製常見的一些幾何圖形,如點、折線、多邊形、圓、矩形等等。先來看下實例化一個Draw類的參數。
這裏重點需要關注的的幾個參數:
type: 繪圖的幾何類型
source: 源,必須是矢量源,用於承載你繪製的圖形要素
freehand: 徒手模式,值爲真時可以鼠標跟隨繪製,不用點擊地圖。
2、實例化及用法
1)畫點
//創建源及圖層
var source = new ol.source.Vector();
var layer = new ol.layer.Vector({
source: source
})
map.addLayer(layer);
//畫點功能
var draw = new ol.interaction.Draw({
type: 'Point',
source: source,
free: false
})
map.addInteraction(draw);
這段代碼即可實現繪製點操作,圖層加載完後,在地圖是單擊一次即畫下一個點。
2)畫其它幾何
如果要繪製其它幾何,修改draw中的type參數即可。幾何類型對應的字符串如下:
折現: LineString,
多邊形: Polygon,
圓: Circle,
矩形:Circle
這裏需要注意矩形: 對應的字符串爲Circle,另外,繪製矩形需要用的ol.interaction.Draw中的一個方法:createBox。上面的draw需要改爲:
draw = new ol.interaction.Draw({
source: source,
type: 'Circle',
freehand: false,
geometryFunction: ol.interaction.Draw.createBox();
});
geometryFunction參數可用於繪製更復雜的幾何。
3、繪圖類型切換
對上面的代碼稍微進行加工,用來實現在不同繪圖類型見的切換。
var drawing = function(type){
return new ol.interaction.Draw({
type: type,
source: source,
free: false
})
}
draw = drawing('Point');
var addInteraction = function(type){
map.removeInteraction(draw);
draw = drawing(type);
map.addInteraction(draw);
}
每次切換調用addInteraction方法即可。