注:当前使用的是 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 </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.target
let output = 0
if (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 = null
measureTooltipElement = null
createMeasureTooltip()
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 = 0
if (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:4326
area = 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 </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 = null
let measureTooltip = null
const 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.target
let output = 0
if (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 = null
measureTooltipElement = null
createMeasureTooltip()
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 = 0
if (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:4326
area = 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>
如果你喜欢本文的话,可以点赞、收藏哦!也可以关注我的微信公众号,不定时更新有关WebGIS开发相关内容。
往期精彩推荐:
原文始发于微信公众号(GIS之路):OpenLayers加载常用控件(九)
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/234675.html