运行时选择正方形画出来是点,代码可以运行,没有出现问题,这是什么原因呢?
<!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>Document</title>
<script src="./lib/include-openlayers-local.js"></script>
<script src="./JS/gaode.js"></script>
<script src="./JS/interaction.js"></script>
</head>
<body>
<div id="menu">
<span>几何形状类型:</span>
<select id="type">
<option value="default">无</option>
<option value="Point">点</option>
<option value="LineString">线</option>
<option value="Circle">圆</option>
<option value="Polygon">多边形</option>
<option value="Square">正方形</option>
<option value="Box">长方形</option>
</select>
</div>
<div id="mapCon"></div>
<script>
const map = new ol.Map({
target:'mapCon',
layers:[gaode],
view:new ol.View({
center:[114,30],
projection:'EPSG:4326',
zoom:4,
}),
})
const source = new ol.source.Vector({ wrapX: false })
const layer = new ol.layer.Vector({ source: source })
map.addLayer(layer)
let draw = null
// 监听下拉框改变事件(change)
const select = document.querySelector('#type')
select.addEventListener('change', function(){
console.log(this.value)
//1、清空旧画笔
source.clear()
// 2、移除旧画笔
if (draw) {
map.removeInteraction(draw)
}
// 3、创建新画笔
draw = createDraw(source, this.value)
map.addInteraction(draw)
})
</script>
</body>
</html>
function createDraw(source, type, callback) {
let geometryFunction = null
let maxPoints = null
const support = ['Point','LineString','Circle','Polygon','Suqare','Box']
if(!support.includes(type)) {
type='Point'//默认值位点
}
if(type == 'Square') {
//特殊处理
type = 'Circle'
geometryFunction = ol.interaction.Draw.createRegularPolygon(4)
}else if(type == 'Box') {
//特殊处理
type = 'LineString'
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
}
maxPoints = 2
}
let draw = null
draw = new ol.interaction.Draw({
source:source,
type:type,
geometryFunction:geometryFunction,
maxPoints:maxPoints,
})
// 短路运算
callback && draw.on('drawend',callback)
return draw
}
WebGIS?