<body>
<div id="menu">
<label>几何图形类型:</label>
<select id="type">
<option value="None">无</option>
<option value="Point">点</option>
<option value="LineString">线</option>
<option value="Polygon">多边形</option>
<option value="Circle">圆</option>
<option value="Square">正方形</option>
<option value="Box">长方形</option>
</select>
</div>
<div id="map"></div>
<script>
var map=new ol.Map({
target:'map',
layer:[],
view:new ol.View({
center:[0,0],
zoom:2
})
});//初始化地图
var OSM=new ol.layer.Tile({
source:new ol.source.OSM()
});
map.addLayer(OSM);//添加地图数据
var selectedType=document.getElementById("type");
var draw;//绘制对象
//绘制绘制层
var source=new ol.source.Vector({wrapX:false});
var vector=new ol.layer.Vector({
source:source,
style:new ol.style.Style({
fill:new ol.style.Fill({
color:'rgba(255,255,255,.2)'
}),
stroke:({
stroke:new ol.style.Stroke({
color:'#ffcc33',
width:2
})
}),
image:new ol.style.Circle({
radius:7,
fill:new ol.style.Fill({
color:'#ffcc33'
})
})
})
});
map.addLayer(vector);
selectedType.onchange=function(e){
map.removeInteraction(draw);//移除绘制图形
addInteraction();
};
addInteraction();//添加交互绘制功能控件
function addInteraction(){
var value=selectedType.value;
if(value!=="None"){
if(source==null){
source=new ol.source.Vector({
wrapX:false
});
vector.setSource(source);
}
var geometryFunction,maxPoints;
if(value==="Square"){
value='Circle';
geometryFunction=ol.interaction.Draw.createRegularPolygon(4);
}else if(value==="Box"){
value='LineString';
maxPoints=2;
geometryFunction=function(coordinates,geometry){
if(!geometry){
geometry=new ol.geom.Polygon(null);
}
var start=coordinates[0];
var end=coordinates[1];
geometry.setCoordinates([
[start,[start[0],end[1]],end,[end[0],start[1]],start]
]);
return geometry;
};
}
draw= new ol.interaction.Draw({
source:source,
type:/**@type {ol,geom.GeometryType}*/(value),
geometryFunction:geometryFunction,
maxPoints:maxPoints
});
map.addInteraction(draw);
}else{
source=null;
vector.setSource(source);
}
}
</script>
</body>