当前位置: 首页 > article >正文

OpenLayers 加载测量控件

注:当前使用的是 ol 5.3.0 版本,天地图使用的key请到天地图官网申请,并替换为自己的key

地图控件是一些用来与地图进行简单交互的工具,地图库预先封装好,可以供开发者直接使用。OpenLayers具有大部分常用的控件,如缩放、导航、鹰眼、比例尺、旋转、鼠标位置等。

这些控件都是基于 ol.control.Control基类进行封装的,可以通过Map对象的controls属性或者调用addControl方法添加到地图中。地图控件通过HTML插入到Map页面,可以利用CSS调整地图控件样式。OpenLayers初始化地图时利用ol.control.default默认加载了缩放控件(ol.control.Zoom

本节主要介绍创建测量控件

1. 创建绘制对象结构

创建绘制对象结构

<div class="measure-control" id="measure-control"><label>Geometry type &nbsp;</label><select id="select-type"><option value="length">Length</option><option value="area">Area</option></select><label class="checkbox"><input type="checkbox" id="geodesic"/>use geodesic measures</label>
</div>

测量工具及测量提示框样式。

.measure-control {position: relative;background: #434343a8;width: 30%;margin: 0 auto;top: 19px;padding: 5px 10px;border-radius: 5px;color: #fff;
}/*提示框信息样式*/
.tooltip{position:relative;background:rgba(0,0,0,.5);border-radius:4px;color:#ffffff;padding:4px 8px;opacity:0.7;white-space:nowrap
}
.tooltip-measure{opacity:1;font-weight:bold
}
.tooltip-static{background-color:#ffcc33;color:black;border:1px solid white
}
.tooltip-measure:before,.tooltip-static:before{border-top: 6px solid rgba(0, 0, 0, 0.5);border-right: 6px solid transparent;border-left: 6px solid transparent;content: "";position: absolute;bottom: -6px;margin-left: -7px;left: 50%;
}
.tooltip-static:before {border-top-color: #ffcc33;
}

2. 创建矢量图层

创建矢量图层需要添加矢量数据源,然后添加矢量图层并设置其样式。

// 创建矢量图层
const vectorSource = new ol.source.Vector()
const vectorLayer = new ol.layer.Vector({source: vectorSource,style: new ol.style.Style({fill: new ol.style.Fill({// 填充色color:'rgba(255,255,255,0.2)'}),stroke: new ol.style.Stroke({color: '#ffcc33', // 边线颜色width: 2.5    // 边线宽度}),// 圆形点样式image: new ol.style.Circle({radius: 7, // 圆形点半径fill: new ol.style.Fill({color:'#ffcc33' // 圆形点填充色})})})
})
map.addLayer(vectorLayer)

3. 添加绘制交互对象

监听选择绘制类型,根据不同类型绘制几何对象

function addInteraction() {const type = selectType.value === 'area' ? 'Polygon' : 'LineString'draw = new ol.interaction.Draw({source: vectorSource,type: type,style: new ol.style.Style({fill: new ol.style.Fill({color:"rgba(255,255,255,0.2)"}),stroke: new ol.style.Stroke({color:"#ffcc33",lineDash:[10,10],width:2}),image: new ol.style.Circle({radius: 5,fill: new ol.style.Fill({color:'rgba(255,255,255,0.2)'})})})})map.addInteraction(draw)createMeasureTooltip() // 测量工具提示框createHelpTooltip() // 帮助信息提示框框let listener = null// 监听开始绘制事件draw.on('drawstart', function (evt) {// 绘制要素sketch = evt.feature// 绘制坐标let tooltipCoord = evt.coordinate// 绑定change事件,根据绘制几何图形类型得到测量距离或者面积,并将其添加到测量工具提示框listener = sketch.getGeometry().on('change', evt=> {// 绘制的几何对象const geom = evt.targetlet output = 0if (geom instanceof ol.geom.Polygon) {output = formatArea(geom)tooltipCoord = geom.getInteriorPoint().getCoordinates()} else {output = formatLength(geom)tooltipCoord = geom.getLastCoordinate()}// 将测量值添加到提示框measureTooltipElement.innerHTML = output// 设置测量提示工具框的位置measureTooltip.setPosition(tooltipCoord)})}, this)draw.on('drawend', function(evt) {measureTooltipElement.className = 'tooltip tooltip-static'measureTooltip.setOffset([0, -7])sketch = nullmeasureTooltipElement = nullcreateMeasureTooltip()ol.Observable.unByKey(listener)},this)
}

4. 创建帮助信息提示框

function createHelpTooltip() {if (helpTooltip) {helpTooltipElement.parentNode.removeChild(helpTooltipElement)}helpTooltipElement = document.createElement('div')helpTooltipElement.className = 'tooltip hidden'helpTooltip = new ol.Overlay({element: helpTooltipElement,offset: [15, 0],positioning:'center-left'})map.addOverlay(helpTooltip)
}

5. 创建测量提示框

function createMeasureTooltip() {if (measureTooltipElement) {measureTooltipElement.parentNode.removeChild(measureTooltipElement)}measureTooltipElement = document.createElement('div') measureTooltipElement.className = 'tooltip tooltip-measure'measureTooltip = new ol.Overlay({element: measureTooltipElement,offset: [0, -15],positioning:'bottom-center'})map.addOverlay(measureTooltip)
}

6. 创建面积与长度测量方法

// 创建距离测算方法
function formatLength(line) {let length = 0if (geodesicCheckBox.checked) {// 经纬度测量,曲面面积const sourcePrj = map.getView().getProjection()length = ol.sphere.getLength(line,{'projection':sourcePrj,'radius':678137})} else {length = Math.round(line.getLength()*100)/100}let output = 0;if (length > 100) {output = (Math.round(length / 1000 * 100) / 100) + ' ' + 'km'; //换算成KM单位} else {output = (Math.round(length * 100) / 100) + ' ' + 'm'; //m为单位}return output;//返回线的长度
}
// 创建面积测算方法
function formatArea (polygon) {let area = 0;if (geodesicCheckBox.checked) {//若使用测地学方法测量const sourceProj = map.getView().getProjection();//地图数据源投影坐标系const geom = (polygon.clone().transform(sourceProj, 'EPSG:4326')); //将多边形要素坐标系投影为EPSG:4326area = Math.abs(ol.sphere.getArea(geom, { "projection": sourceProj, "radius": 6378137 })); //获取面积} else {area = polygon.getArea();//直接获取多边形的面积}let output = 0;if (area > 10000) {output = (Math.round(area / 1000000 * 100) / 100) + ' ' + 'km<sup>2</sup>'; //换算成KM单位} else {output = (Math.round(area * 100) / 100) + ' ' + 'm<sup>2</sup>';//m为单位}return output; //返回多边形的面积
};

7. 监听鼠标移动事件

// 添加地图鼠标移动事件
const drawPolygonMsg = "Click to continue drawing the polygon"
const drawLineMsg = "Click to continue drawing the line"
// 鼠标移动事件处理函数
const pointerMoveHandler = evt=> {if (evt.dragging) {return}let helpMsg = "Click to start drawing" // 默认提示信息// 判断绘制的几何类型,设置对应信息提示框if (sketch) {const geom = sketch.getGeometry()if (geom instanceof ol.geom.Polygon) {helpMsg = drawPolygonMsg} else if (geom instanceof ol.geom.LineString) {helpMsg = drawLineMsg}}helpTooltipElement.innerHTML = helpMsg // helpTooltip.setPosition(evt.coordinate)$(helpTooltipElement).removeClass('hidden') // 移除隐藏样式}
map.on('pointermove', pointerMoveHandler) // 绑定鼠标移动事件,动态显示帮助信息提示框
$(map.getViewport()).on('mouseout', evt=> {$(helpTooltipElement).addClass('hidden')
})

8. 完整代码

其中libs文件夹下的包需要更换为自己下载的本地包或者引用在线资源。

<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>加载测量控件</title><meta charset="utf-8" /><script src="../libs/js/ol-5.3.3.js"></script><script src="../libs/js/jquery-2.1.1.min.js"></script><link rel="stylesheet" href="../libs/css//ol.css"><style>* {padding: 0;margin: 0;font-size: 14px;font-family: '微软雅黑';}html,body{width:100%;height:100%;}#map {position: absolute;width: 100%;height: 100%;}.measure-control {position: relative;background: #434343a8;width: 30%;margin: 0 auto;top: 19px;padding: 5px 10px;border-radius: 5px;color: #fff;}/*提示框信息样式*/.tooltip{position:relative;background:rgba(0,0,0,.5);border-radius:4px;color:#ffffff;padding:4px 8px;opacity:0.7;white-space:nowrap}.tooltip-measure{opacity:1;font-weight:bold}.tooltip-static{background-color:#ffcc33;color:black;border:1px solid white}.tooltip-measure:before,.tooltip-static:before{border-top: 6px solid rgba(0, 0, 0, 0.5);border-right: 6px solid transparent;border-left: 6px solid transparent;content: "";position: absolute;bottom: -6px;margin-left: -7px;left: 50%;}.tooltip-static:before {border-top-color: #ffcc33;}</style>
</head>
<body><div id="map" title="地图显示"></div><div class="measure-control" id="measure-control"><label>Geometry type &nbsp;</label><select id="select-type"><option value="length">Length</option><option value="area">Area</option></select><label class="checkbox"><input type="checkbox" id="geodesic"/>use geodesic measures</label></div>
</body>
</html>
<script>//==============================================================================////============================天地图服务参数简单介绍============================////================================vec:矢量图层=================================////================================img:影像图层=================================////================================cva:注记图层=================================////=========================其中:_c表示经纬度,_w表示投影=======================////==============================================================================//const TDTImgLayer = new ol.layer.Tile({title: "天地图影像图层",source: new ol.source.XYZ({url: "http://t0.tianditu.com/DataServer?T=img_c&x={x}&y={y}&l={z}&tk=2a890fe711a79cafebca446a5447cfb2",attibutions: "天地图注记描述",crossOrigin: "anoymous",wrapX: false})})const TDTVecLayer = new ol.layer.Tile({title: "天地图矢量图层",source: new ol.source.XYZ({url: "http://t0.tianditu.com/DataServer?T=vec_c&x={x}&y={y}&l={z}&tk=2a890fe711a79cafebca446a5447cfb2",attibutions: "天地图注记描述",crossOrigin: "anoymous",wrapX: false})})const map = new ol.Map({target: "map",loadTilesWhileInteracting: true,view: new ol.View({// center: [11444274, 12707441],center: [12992990, 13789010],// center: ol.proj.fromLonLat([102,25.5]),zoom: 15,worldsWrap: true,minZoom: 1,maxZoom: 20,}),controls: ol.control.defaults().extend([new ol.control.MousePosition()])})map.addLayer(TDTVecLayer)map.addLayer(TDTImgLayer)// 创建矢量图层const vectorSource = new ol.source.Vector()const vectorLayer = new ol.layer.Vector({source: vectorSource,style: new ol.style.Style({fill: new ol.style.Fill({// 填充色color:'rgba(255,255,255,0.2)'}),stroke: new ol.style.Stroke({color: '#ffcc33', // 边线颜色width: 2.5// 边线宽度}),// 顶点样式image: new ol.style.Circle({radius: 7,fill: new ol.style.Fill({color:'#ffcc33'})})})})map.addLayer(vectorLayer)let draw = null // 绘制对象let sketch = null // 当前绘制要素let helpTooltipElement = null // 创建提示框let helpTooltip = null// 创建测量工具提示框let measureTooltipElement = nulllet measureTooltip = nullconst geodesicCheckBox = document.getElementById('geodesic')// 创建测量交互函数const selectType = document.getElementById('select-type')selectType.onchange = evt=> {// 移除交互式控件if (draw) {map.removeInteraction(draw)}// 添加交互式控件进行测量addInteraction()}addInteraction()function addInteraction() {const type = selectType.value === 'area' ? 'Polygon' : 'LineString'draw = new ol.interaction.Draw({source: vectorSource,type: type,style: new ol.style.Style({fill: new ol.style.Fill({color:"rgba(255,255,255,0.2)"}),stroke: new ol.style.Stroke({color:"#ffcc33",lineDash:[10,10],width:2}),image: new ol.style.Circle({radius: 5,fill: new ol.style.Fill({color:'rgba(255,255,255,0.2)'})})})})map.addInteraction(draw)createMeasureTooltip() // 测量工具提示框createHelpTooltip() // 帮助信息提示框框let listener = null// 监听开始绘制事件draw.on('drawstart', function (evt) {// 绘制要素sketch = evt.feature// 绘制坐标let tooltipCoord = evt.coordinate// 绑定change事件,根据绘制几何图形类型得到测量距离或者面积,并将其添加到测量工具提示框listener = sketch.getGeometry().on('change', evt=> {// 绘制的几何对象const geom = evt.targetlet output = 0if (geom instanceof ol.geom.Polygon) {output = formatArea(geom)tooltipCoord = geom.getInteriorPoint().getCoordinates()} else {output = formatLength(geom)tooltipCoord = geom.getLastCoordinate()}// 将测量值添加到提示框measureTooltipElement.innerHTML = output// 设置测量提示工具框的位置measureTooltip.setPosition(tooltipCoord)})}, this)draw.on('drawend', function(evt) {measureTooltipElement.className = 'tooltip tooltip-static'measureTooltip.setOffset([0, -7])sketch = nullmeasureTooltipElement = nullcreateMeasureTooltip()ol.Observable.unByKey(listener)},this)}function createHelpTooltip() {if (helpTooltip) {helpTooltipElement.parentNode.removeChild(helpTooltipElement)}helpTooltipElement = document.createElement('div')helpTooltipElement.className = 'tooltip hidden'helpTooltip = new ol.Overlay({element: helpTooltipElement,offset: [15, 0],positioning:'center-left'})map.addOverlay(helpTooltip)}function createMeasureTooltip() {if (measureTooltipElement) {measureTooltipElement.parentNode.removeChild(measureTooltipElement)}measureTooltipElement = document.createElement('div') measureTooltipElement.className = 'tooltip tooltip-measure'measureTooltip = new ol.Overlay({element: measureTooltipElement,offset: [0, -15],positioning:'bottom-center'})map.addOverlay(measureTooltip)}// 创建面积与距离测算方法function formatLength(line) {let length = 0if (geodesicCheckBox.checked) {// 经纬度测量,曲面面积const sourcePrj = map.getView().getProjection()length = ol.sphere.getLength(line,{'projection':sourcePrj,'radius':678137})} else {length = Math.round(line.getLength()*100)/100}let output = 0;if (length > 100) {output = (Math.round(length / 1000 * 100) / 100) + ' ' + 'km'; //换算成KM单位} else {output = (Math.round(length * 100) / 100) + ' ' + 'm'; //m为单位}return output;//返回线的长度}function formatArea (polygon) {let area = 0;if (geodesicCheckBox.checked) {//若使用测地学方法测量const sourceProj = map.getView().getProjection();//地图数据源投影坐标系const geom = (polygon.clone().transform(sourceProj, 'EPSG:4326')); //将多边形要素坐标系投影为EPSG:4326area = Math.abs(ol.sphere.getArea(geom, { "projection": sourceProj, "radius": 6378137 })); //获取面积} else {area = polygon.getArea();//直接获取多边形的面积}let output = 0;if (area > 10000) {output = (Math.round(area / 1000000 * 100) / 100) + ' ' + 'km<sup>2</sup>'; //换算成KM单位} else {output = (Math.round(area * 100) / 100) + ' ' + 'm<sup>2</sup>';//m为单位}return output; //返回多边形的面积};// 添加地图鼠标移动事件const drawPolygonMsg = "Click to continue drawing the polygon"const drawLineMsg = "Click to continue drawing the line"// 鼠标移动事件处理函数const pointerMoveHandler = evt=> {if (evt.dragging) {return}let helpMsg = "Click to start drawing" // 默认提示信息// 判断绘制的几何类型,设置对应信息提示框if (sketch) {const geom = sketch.getGeometry()if (geom instanceof ol.geom.Polygon) {helpMsg = drawPolygonMsg} else if (geom instanceof ol.geom.LineString) {helpMsg = drawLineMsg}}helpTooltipElement.innerHTML = helpMsg // helpTooltip.setPosition(evt.coordinate)$(helpTooltipElement).removeClass('hidden') // 移除隐藏样式}map.on('pointermove', pointerMoveHandler) // 绑定鼠标移动事件,动态显示帮助信息提示框$(map.getViewport()).on('mouseout', evt=> {$(helpTooltipElement).addClass('hidden')})
</script>

OpenLayers示例数据下载,请回复关键字:ol数据

全国信息化工程师-GIS 应用水平考试资料,请回复关键字:GIS考试

【GIS之路】 已经接入了智能助手,欢迎关注,欢迎提问。

欢迎访问我的博客网站-长谈GIShttp://shanhaitalk.com

都看到这了,不要忘记点赞、收藏 + 关注

本号不定时更新有关 GIS开发 相关内容,欢迎关注 !

http://www.lryc.cn/news/2385417.html

相关文章:

  • .NET ORM开发手册:基于SqlSugar的高效数据访问全攻略
  • 【PostgreSQL】数据探查工具1.0研发可行性方案
  • C++ 内存管理与单例模式剖析
  • 算法学习——从零实现循环神经网络
  • win10使用nginx做简单负载均衡测试
  • 2025电工杯数学建模B题思路数模AI提示词工程
  • 软考软件评测师——软件工程之开发模型与方法
  • 前端表单中 `readOnly` 和 `disabled` 属性的区别
  • 【日志软件】hoo wintail 的替代
  • OceanBase数据库全面指南(基础入门篇)
  • 异步处理与事件驱动中的模型调用链设计
  • redis配置带验证的主从复制
  • Ollama-OCR:基于Ollama多模态大模型的端到端文档解析和处理
  • OpenCV CUDA 模块中图像过滤------创建一个拉普拉斯(Laplacian)滤波器函数createLaplacianFilter()
  • 图论学习笔记 3
  • 在单片机中如何在断电前将数据保存至DataFlash?
  • 【将WPS设置为默认打开方式】--突然无法用WPS打开文件
  • 电子人的分水岭-FPGA模电和数电
  • (6)python爬虫--selenium
  • Python之两个爬虫案例实战(澎湃新闻+网易每日简报):附源码+解释
  • HarmonyOS NEXT~鸿蒙系统与mPaaS三方框架集成指南
  • 系统安全及应用学习笔记
  • STC89C52RC/LE52RC
  • ✨ PLSQL卡顿优化
  • yum命令常用选项
  • python+vlisp实现对多段线范围内土方体积的计算
  • 鸿蒙Flutter实战:25-混合开发详解-5-跳转Flutter页面
  • APM32小系统键盘PCB原理图设计详解
  • 【C/C++】多线程开发:wait、sleep、yield全解析
  • uint8_t是什么数据类型?