描述在前
在使用地图的应用场景中,避免不了与地图进行几何图形的交互,上一节讲述的画点面线只适合用代码就行图形添加,鼠标交互很少,且远未形成体系,所以这章节记录一下,Openlayer中专门用来鼠标画几何图形的工具 ol.interaction.Draw。代码请向下看。
代码在后
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/ol@v8.2.0/dist/ol.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@v8.2.0/ol.css">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style>
html { height: 100% }
body { height: 100%;margin: 0px;padding: 0px }
ul,li{
margin:0;
padding:0;
list-style:none;
}
p{font-size:12px;}
li{
line-height:28px;
}
#container{
width: 100%;
height: 100%;
overflow: hidden;
position: absolute;
}
.unselectMap{
float: left;
box-shadow: rgba(0, 0, 0, 0.35) 2px 2px 3px;
border-left: 1px solid rgb(139, 164, 220);
border-top: 1px solid rgb(139, 164, 220);
border-bottom: 1px solid rgb(139, 164, 220);
background: rgb(255, 255, 255);
padding: 2px 6px;
font-style: normal;
font-variant: normal;
font-kerning: auto;
font-optical-sizing: auto;
font-feature-settings: normal;
font-variation-settings: normal;
font-stretch: normal;
font-size: 12px;
line-height: 1.3em;
font-family: arial, sans-serif;
text-align: center;
white-space: nowrap;
border-radius: 3px 0px 0px 3px;
color: rgb(0, 0, 0);
}
.selectMap{
float: left;
box-shadow: rgba(0, 0, 0, 0.35) 2px 2px 3px;
border-width: 1px;
border-style: solid;
border-color: rgb(139, 164, 220);
background: rgb(142, 168, 224);
padding: 2px 6px;
font: bold 12px / 1.3em arial, sans-serif;
text-align: center;
white-space: nowrap;
border-radius: 0px 3px 3px 0px;
color: rgb(255, 255, 255);
}
.mapChange{
margin-left: 4rem;
padding-left: 40px;
padding-top: 10px;
white-space: nowrap;
cursor: pointer;
position: absolute;
z-index: 1;
text-size-adjust: none;
}
.drawing-panel {
z-index: 999;
position: fixed;
bottom: 1rem;
right: 0.2rem;
margin-left: 0.2rem;
padding: 0.1rem 0.1rem;
border-radius: .25rem;
background-color: transparent;
/* 设置阴影 */
box-shadow: 0 0px 0px 0 rgba(27, 142, 236, 0.5);
}
.pos {
width: 150px;
height: 30px;
float: left;
background-color: #fff;
color: rgba(27, 142, 236, 1);
font-size: 13px;
border:1px solid rgba(27, 142, 236, 1);
border-radius: 5px;
margin: 0 5px;
text-align: center;
line-height: 30px;
}
.pos2 {
width: 180px;
height: 30px;
float: left;
background-color: #fff;
color: red;
font-size: 13px;
border:1px solid rgba(27, 142, 236, 1);
border-radius: 5px;
margin: 0 5px;
text-align: center;
line-height: 30px;
}
/* 比例尺的样式 */
.my-scale-line {
position: absolute;
right: 75px;
font-weight: 700;
font-size: 12px;
color: white;
bottom: 60px;
left: auto;
border: 2px solid white;
border-top: none;
text-align: center;
background-color: hsla(0, 0%, 100%, 0);
height: 8px;
line-height: 0;
}
/* 设置缩放按钮与滑块的样式 */
.ol-zoom .ol-zoom-out {
margin-top: 200px;
}
.ol-zoomslider {
background-color: transparent;
top: calc(0.5em + 2px + 1px + 1.14 * 1.375em);
}
.ol-touch .ol-zoom .ol-zoom-out {
margin-top: 212px;
}
.ol-touch .ol-zoomslider {
top: 2.75em;
}
.ol-zoom-in.ol-has-tooltip:hover [role=tooltip],
.ol-zoom-in.ol-has-tooltip:focus [role=tooltip] {
top: 3px;
}
.ol-zoom-out.ol-has-tooltip:hover [role=tooltip],
.ol-zoom-out.ol-has-tooltip:focus [role=tooltip] {
top: 232px;
}
</style>
<title>Tool</title>
</head>
<body>
<div id="container"></div>
<script>
// AMapLayer 为普通地图的 Layer
AMapLayer = new ol.layer.Tile({
// 每个图层有对应的数据源(Source)
source: new ol.source.XYZ({
// 该url为高德瓦片地图地址
url:'https://wprd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}'
})
});
// 把整个地图看作一个容器(Map)
var map = new ol.Map({
target: 'container',
// 核心为地图图层(Layer)
layers: [AMapLayer],
// 并由地图视图(View)进行地图表现
view: new ol.View({
//设定默认坐标系
projection: 'EPSG:3857',
//设定中心点,因为默认坐标系为 3587,所以要将我们常用的经纬度坐标系4326 转换为 3587坐标系
center: ol.proj.transform([120.266053,31.550228], 'EPSG:4326', 'EPSG:3857'),
// 默认显示级别,相当于瓦片地图的 Z 级别
zoom: 5,
// 最小显示级别
minZoom:3,
// 最大显示级别
maxZoom:19
})
});
// 默认显示普通地图,所以将 AMapLayer 的 Visible 设定为true,其他设定为fasle
AMapLayer.setVisible(true);
// 创建坐标显示框
function createMapShowBar(){
let htmlBottomShow = "";
htmlBottomShow += "<li id=\"position0\" class=\"pos\">0.0,0.0</li>";
let htmlBottomUl = document.createElement("ul");
htmlBottomUl.className = "drawing-panel";
htmlBottomUl.innerHTML = htmlBottomShow;
document.body.appendChild(htmlBottomUl);
}
// 创建地图形式切换按钮
function createDrawBar(){
let htmllet = "";
htmllet += "<div title=\"画点\" id=\"point\" class=\"unselectMap\">画点</div>";
htmllet += "<div title=\"画线\" id=\"lineString\" class=\"unselectMap\">画线</div>";
htmllet += "<div title=\"画多边形\" id=\"polygon\" class=\"unselectMap\">画多边形</div>";
htmllet += "<div title=\"画圆\" id=\"circle\" class=\"unselectMap\">画圆</div>";
htmllet += "<div title=\"画正多边形\" id=\"rPolygon\" class=\"unselectMap\">画正多边形</div>";
let p = document.createElement("div");
p.className = "mapChange";
p.innerHTML = htmllet;
document.body.appendChild(p);
}
//
function drawChange() {
createMapShowBar();
createDrawBar();
var point=document.getElementById("point");
var lineString=document.getElementById("lineString");
var polygon=document.getElementById("polygon");
var circle=document.getElementById("circle");
var rPolygon=document.getElementById("rPolygon");
point.addEventListener('click',function(){
createDrawTool('Point');
})
lineString.addEventListener('click',function(){
createDrawTool('LineString');
})
polygon.addEventListener('click',function(){
createDrawTool('Polygon',6);
})
circle.addEventListener('click',function(){
createDrawTool('Circle');
})
rPolygon.addEventListener('click',function(){
createDrawTool('Circle',6);
})
}
drawChange();
// 添加比例尺
map.addControl(new ol.control.ScaleLine({
units: 'metric', // 设置单位
className: 'my-scale-line'
}));
// 监听鼠标移动,显示实时坐标
var moveSignal = map.on('pointermove',(evt)=>{
let movePoint = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326')
document.getElementById('position0').innerText = movePoint[0].toFixed(7) + "," + movePoint[1].toFixed(7);
});
// 定义一个画图的图层,用于画图工具画图
var drawLayer = new ol.layer.Vector({
// 定义图层数据源,给图层数据源添加数据
source: new ol.source.Vector(),
// 定义该图层中的图形样式
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(0, 255, 0, 0.2)',
}),
stroke: new ol.style.Stroke({
color: 'green',
width: 2,
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33',
}),
}),
}),
});
// 将画图的图层添加给地图
map.addLayer(drawLayer);
// 创建绘图工具
var draw;
function createDrawTool(type,num) {
// 移除上一个画图工具
map.removeInteraction(draw);
let geometryFunction=null;
// 当需要画正多边形时,需要使用如下代码,type为Circle,num为多边形边数
if(type=="Circle"&&num>=2) {
geometryFunction= ol.interaction.Draw.createRegularPolygon(num);
}
// 定义画图工具
draw = new ol.interaction.Draw({
source: drawLayer.getSource(),
type: type,
geometryFunction: geometryFunction, //几何信息变更时的回调函数
});
// 获取到双击接口
var doubleClickZoom= map.getInteractions().getArray().find(
interaction => {
return interaction instanceof ol.interaction.DoubleClickZoom;
}
);
// 在画图开始的时候屏蔽画图后双击放大信号
draw.on('drawstart', function(evt) {
map.removeInteraction(doubleClickZoom);
}, this);
// 获取到画图结束的信号,进行画图后处理
draw.on('drawend',(evt)=>{
let geom = evt.feature.getGeometry();
if (geom instanceof ol.geom.Point) {
// 获取点坐标
let points =geom.getCoordinates();
console.log("Point",points);
} else if (geom instanceof ol.geom.LineString) {
// 获取线段点位坐标
let points = geom.getCoordinates();
console.log("LineString",points);
} else if (geom instanceof ol.geom.Polygon) {
// 多边形为多维数组,需要取出第一个数组坐标
let points = geom.getCoordinates()[0];
console.log("Polygon",points);
} else if (geom instanceof ol.geom.Circle) {
// 起始点为中心点
let point0 = geom.getFirstCoordinate();
// 结束点为圆边上的点
let point1 = geom.getLastCoordinate();
// 进行投影坐标向大地坐标系的转换
let changePoint0 = ol.proj.transform(point0, 'EPSG:3857', 'EPSG:4326')
let changePoint1 = ol.proj.transform(point0, 'EPSG:3857', 'EPSG:4326')
console.log("Circle",changePoint0,changePoint1);
}
});
map.addInteraction(draw);
}
</script>
</body>
</html>
实现效果如下
最后总结
以上介绍了如何使用 Openlayer 的画图工具,并在画图完成,后处理中获取到画图的坐标,拿到坐标后就可以针对项目性的需求进行拓展了。
记录完成。
下次,我们记录如何拖动修改画图工具所画的图形。