前言
缺少前置学习使用资料,请自行查阅:[https://blog.csdn.net/weixin_44402694/article/details/123110136](https://blog.csdn.net/weixin_44402694/article/details/123110136)
以下示例使用到的公共静态资料,不建议下载,建议官网自行下载超图Build资源,示例所涉及图片会在示例使用到时提供出来。如有需要可下载:[https://download.csdn.net/download/weixin_44402694/82180350](https://download.csdn.net/download/weixin_44402694/82180350)。
标绘线段:Cesium.DrawHandler绘制线段Cesium.DrawMode.Line。
使用
-
效果
-
完整代码
<!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>
<link href="./public/Build/Cesium/Widgets/widgets.css" rel="stylesheet" />
<script
type="text/javascript"
src="./public/Build/Cesium/Cesium.js"
></script>
<style>
* {
margin: 0;
padding: 0;
}
html,
body,
#cesium-container {
width: 100%;
height: 100%;
}
.panel {
position: fixed;
left: 10px;
top: 10px;
z-index: 1;
background-color: #fff;
}
.panel .btn {
cursor: pointer;
}
.tooltip {
position: fixed;
left: 0;
top: 0;
background: rgba(0, 0, 0, 0.4);
padding: 4px;
border-radius: 4px;
display: none;
z-index: 1;
color: #fff;
}
</style>
</head>
<body>
<div id="cesium-container" />
<div class="panel">
<p class="btn">点击绘制线</p>
<p class="btn">清除线</p>
<p class="btn">关闭绘制</p>
</div>
<div class="tooltip"></div>
<script>
let viewer, handlerLine, linePoints
const tooltip = document.querySelector('.tooltip')
window.onload = function () {
viewer = new Cesium.Viewer('cesium-container', {
navigation: false,
})
readyDrawLineHandler()
drawLineHandler()
}
// 点击按钮触发对应事件
function drawLineHandler() {
const btns = document.querySelectorAll('.panel .btn')
btns[0].addEventListener('click', () => {
handlerLine.deactivate() // 先触发一次关闭绘制
handlerLine.clear() // 先清除一次之前的点位
handlerLine.activate() // 触发绘制
})
btns[1].addEventListener('click', () => {
// 清除已存在的点位 会同时关闭当前存在的绘制
handlerLine.clear()
})
btns[2].addEventListener('click', () => {
// 关闭绘制
handlerLine.deactivate()
})
}
// 绘制程序的准备工作,通过其他方式触发activate
function readyDrawLineHandler() {
handlerLine = new Cesium.DrawHandler(viewer, Cesium.DrawMode.Line)
handlerLine.activeEvt.addEventListener(function (isActive) {
if (isActive) {
viewer.enableCursorStyle = false
viewer._element.style.cursor = ''
document.documentElement.style.cursor = 'pointer'
} else {
viewer.enableCursorStyle = true
document.documentElement.style.cursor = ''
tooltip.style.display = 'none'
}
})
handlerLine.movingEvt.addEventListener(function ({x, y}) {
// 绘制过程中的提示框,根据返回的屏幕坐标设置
tooltip.style.display = 'block'
tooltip.style.left = x + 20 + 'px'
tooltip.style.top = y - 10 + 'px'
if (handlerLine.isDrawing) {
tooltip.innerHTML = '<p>左键点击确定折线中间点</p><p>右键单击结束绘制</p>'
} else {
tooltip.innerHTML = '点击绘制第一个点'
}
})
handlerLine.drawEvt.addEventListener(function (result) {
// 绘制结束(不是关闭绘制),隐藏tooltip,确认最终点位
tooltip.style.display = 'none'
linePoints = result.object.positions
})
}
</script>
</body>
</html>