公司要开始使用openloayers进行项目开发,只好自己研究一下了,并记录一下,如有不足之处欢迎指正
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>交互画点,线,面</title>
<script src="./v6.14.1/build/ol.js"></script>
<link rel="stylesheet" href="./v6.14.1/css/ol.css.map">
<style>
body,
html {
width: 100%;
height: 100%;
}
#map {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<label for="type">选择绘画样式:</label>
<select id="type">
<!-- 一个select选择框选择画绘画的样式 -->
<option value="Point">Point</option>
<option value="LineString">LineString</option>
<option value="MultiLineString">MultiLineString</option>
<option value="Polygon">Polygon</option>
<option value="Circle">Circle</option>
<option value="Square">Square</option>
<option value="Box">Box</option>
<option value="None">None</option>
</select>
<!-- 定义一个地图的容器 -->
<div id="map">
</div>
<script>
// 生成一个地图的类
var map = new ol.Map({
target: "map",
layers: [new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'http://t3.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=自己的'
})
}),
new ol.layer.Tile({
source: new ol.source.XYZ({
url: "http://t4.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=自己的",
})
})],
view: new ol.View({
center: [108.93060745, 34.16138567],
projection: 'EPSG:4326',
zoom: 10
})
})
// 创建一个存放绘画的图层
var lineLayer = new ol.layer.Vector({
source: new ol.source.Vector(),
// 绘画的样式
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: "#ff0000",
width: 2
}),
fill: new ol.style.Fill({
color: "red"
}),
image: new ol.style.Circle({
// 点的颜色
fill: new ol.style.Fill({
color: '#F00'
}),
// 圆形半径
radius: 5
}),
}),
})
// 添加图层
map.addLayer(lineLayer)
// 获取选择框的值
var types = document.querySelector('#type')
// 定义一个变量,用来存放绘画的点
let draws;
// 声明一个工具类
function addInteraction() {
// 拿到选择框的值
let type = types.value
// 声明一个下方使用多边形的变量
let geometryFunction;
// 开始进行判断
if (types != 'None') {
switch (type) {
case "Square":
type = 'Circle';
// 生成规则的四边形的图形函数
geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
break;
case 'Box':
type = 'Circle';
// 生成盒形状的图形函数
geometryFunction = ol.interaction.Draw.createBox();
break;
default: break;
}
// 开始添加绘画的交互
draws = new ol.interaction.Draw({
// 绘画的类型
type: type,
// 图层
source: lineLayer.getSource(),
geometryFunction: geometryFunction
})
// 添加交互
map.addInteraction(draws)
}
}
types.addEventListener('change', () => {
// 移除Draw绘图控件
map.removeInteraction(draws);
addInteraction();
});
addInteraction()
// map.addInteraction(new ol.interaction.Draw({
// // type 规定绘画的类型,可以是点、线、面或多边形。
// // type:"LineString", 划线,直线,一条线
// // type: 'MultiLineString', 画出多种线来,折线
// type: "Polygon", //画出多边形,多边形
// // type:'Circle', //画出的是一个圆
// freehand: true,
// source: lineLayer.getSource()
// }))
</script>
</body>
</html>