<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/css/ol.css" />
<script type="text/javascript" src="https://openlayers.org/en/v5.3.0/build/ol.js"></script>
<title>Document</title>
</head>
<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>
</select>
</div>
<div id="map"></div>
<script>
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: [ 91.1, 30.41],
zoom: 4
})
});
var typeSelect = document.getElementById('type'); //绘制类型选择对象
var draw; //ol.Interaction.Draw类的对象
//实例化一个矢量图层Vector作为绘制层
var source = new ol.source.Vector();
var vectorLayer = new ol.layer.Vector({
source: source,
style: new ol.style.Style({
fill: new ol.style.Fill({ //填充样式
color: 'rgba(255, 255, 255, 0.2'
}),
stroke: new ol.style.Stroke({ //线样式
color: '#00c033',
2
}),
image: new ol.style.Circle({ //点样式
radius: 7,
fill: new ol.style.Fill({
color: '#00c033'
})
})
})
});
//将绘制层添加到地图容器中
map.addLayer(vectorLayer);
//用户更改绘制类型触发的事件
typeSelect.onchange = function(e){
map.removeInteraction(draw); //移除绘制图形控件
addInteraction(); //添加绘制图形控件
};
function addInteraction(){
var typeValue = typeSelect.value; //绘制类型
if(typeValue !== 'None'){
var geometryFunction, maxPoints;
if(typeValue === 'Square'){ //正方形
typeValue = 'Circle'; //设置绘制类型为Circle
//设置几何信息变更函数,即创建正方形
geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
}
console.log(typeValue);
//实例化图形绘制控件对象并添加到地图容器中
draw = new ol.interaction.Draw({
source: source,
type: typeValue, //几何图形类型
geometryFunction: geometryFunction, //几何信息变更时的回调函数
maxPoints: maxPoints //最大点数
});
map.addInteraction(draw);
}else{
//清空绘制的图形
source.clear();
}
}
</script>
</body>
</html>
效果图:
最新评论