You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1455 lines
62 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="v5.3.0/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../../../css/pintuer-min.css" type="text/css" />
<style>
.map {
height: 800px;
width: 100%;
}
</style>
<script
language="javascript"
src="../../../../common/script/jquery.js"
type="text/javascript"
></script>
<script
language="javascript"
src="../../../../common/script/pintuer.js"
type="text/javascript"
></script>
<script
language="javascript"
src="../../../../common/script/jquery.bs.js"
type="text/javascript"
></script>
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="v5.3.0/build/ol.js"></script>
<title>OpenLayers example</title>
<style>
/**
* 提示框的样式信息
*/
.tooltip {
position: relative;
background: rgba(0, 0, 0, 0.5);
border-radius: 4px;
color: white;
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>
<h2>My Map</h2>
<div id="map" class="map border"></div>
<div>
<button onclick="addPoint()" type="button">添加点</button>
<button onclick="addText()" type="button">添加文字</button>
<button onclick="addLine()" type="button">添加轨迹</button>
<button onclick="addInteractions()" type="button">添加多边形</button>
<button onclick="addRegularPolygonTest()" type="button">添加扇形</button>
<button onclick="addEventListener()" type="button">添加聚合</button>
<button onclick="getDist()" type="button">计算距离</button>
<button onclick="measure()" type="button">测量</button>
</div>
<script type="text/javascript">
var key = 'd7b1b7243fce9720e4e1ae73e41a47ad';
var drawSource = null;
var draw, snap;
var drawVector = null;
var FancePoints = null;
var popup = null;
//地图创建
drawSource = new ol.source.Vector();
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(), //原始地图
validity: false,
}),
// new ol.layer.Tile({
// source: new ol.source.XYZ({
// url: "http://localhost:9090/mbtiles/index.jsp?mapindex=vecva&zoom={z}&col={x}&row={y}"
// })
// }),
// new ol.layer.Tile({
// source: new ol.source.XYZ({
// url: "http://localhost:9090/mbtiles/index.jsp?mapindex=cia&zoom={z}&col={x}&row={y}"
// }),
// visible: false
// }),
new ol.layer.Vector({
source: drawSource,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(0, 255, 0, 0.3)',
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2,
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33',
}),
}),
}),
}),
],
target: 'map',
view: new ol.View({
projection: 'EPSG:4326',
center: [112.97935279, 28.21347823],
zoom: 15,
}),
controls: ol.control.defaults({
attributionOptions: {
collapsible: false,
},
}),
});
var pDiv = $('#popup');
if (pDiv.length == 0) {
$('body').append('<div id="popup" class=\'bg-main\' style="width:250px;"></div>');
pDiv = $('#popup');
}
//pDiv.popover('destroy');
popup = new ol.Overlay({
element: pDiv[0],
positioning: 'bottom-center',
stopEvent: false,
offset: [0, -50],
});
map.addOverlay(popup);
//pointermove
// map.on('pointermove', function (evt) {
// var feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
// return feature;
// });
// if (feature) {
// var coordinates = feature.getGeometry().getCoordinates();
// popup.setPosition(coordinates);
// pDiv.html('sss');
// pDiv.show();
// } else {
// pDiv.hide();
// }
// });
map.on('singleclick', function (event) {
// map.forEachFeatureAtPixel(event.pixel, feature => {
// 为移动到的feature发送自定义的singleclick消息
//feature.dispatchEvent({type: 'singleclick', event: event});
//});
});
map.on('click', function (evt) {
//debugger
var coordinate = evt.coordinate;
/****************************************************/
//判断当前单击处是否有要素捕获到要素时弹出popup
// feature = map.forEachFeatureAtPixel(evt.pixel, function(feature, layerVetor) { return feature; });
// if (feature) { //捕捉到要素
// if (feature.getProperties().features) { //聚合情况下
// if (feature.getProperties().features.length == 1) { //只有一个要素
// // layer.msg("聚合该处有1个要素")
// featuerInfo = feature.getProperties().features[0].values_.attribute;
// pDiv.innerHTML = ''; //清空popup的内容容器
// addFeatrueInfo(featuerInfo); //在popup中加载当前要素的具体信息
// if (popup.getPosition() == undefined) {
// popup.setPosition(coordinate); //设置popup的位置
// }
// } else { //有多个要素
// //layer.msg("多标记聚合!");
// info_popup.setPosition(undefined);
// }
// } else {
// info_popup.setPosition(undefined);
// }
// } else {
// info_popup.setPosition(undefined);
// }
/******************************************/
});
function addPoint() {
let oneP = new ol.Feature({
geometry: new ol.geom.Point([113.005943, 28.219205]),
});
//oneP.set("desc", _desc);
oneP.setStyle(
new ol.style.Style({
image: new ol.style.Icon(
/** @type {olx.style.IconOptions} */ ({
color: '#8959A8',
crossOrigin: 'anonymous',
rotation: (45 * (2 * Math.PI)) / 360,
src: webHome + '/common/images/arrow/arrow01.png',
scale: 0.8,
})
),
text: new ol.style.Text({
text: 'A',
scale: 1,
rotation: (45 * (2 * Math.PI)) / 360,
fill: new ol.style.Fill({
color: '#000000',
}),
stroke: new ol.style.Stroke({
color: '#FFFF99',
width: 3.5,
}),
}),
})
);
// UserFeature["d_" + _data.eqpid] = oneP;
var mapLayers = new ol.layer.Vector({
source: new ol.source.Vector({
features: [oneP],
}),
zindex: 20,
});
map.addLayer(mapLayers);
}
function addText() {
let oneP = new ol.Feature({
geometry: new ol.geom.Point([113.006943, 28.219305]),
//geometry: new ol.geom.Circle([113.006943, 28.219305], 20 / map.getView().getProjection().getMetersPerUnit())
});
oneP.on('singleclick', function (evt) {
//var coordinate = evt.coordinate;
alert('aa');
//overlay.setPosition(coordinate);
});
//oneP.set("desc", _desc);
oneP.setStyle(
new ol.style.Style({
fill: new ol.style.Fill({
color: '#0a3399CC',
}),
image: new ol.style.Icon(
/** @type {olx.style.IconOptions} */ ({
color: '#8959A8',
crossOrigin: 'anonymous',
rotation: (45 * (2 * Math.PI)) / 360,
src: webHome + '/common/images/point/point01.png',
scale: 0.5,
})
),
text: new ol.style.Text({
text: '1',
// offsetX:5,
// offsetY:2,
//scale: 1.3,
fill: new ol.style.Fill({
color: '#000000',
}),
stroke: new ol.style.Stroke({
color: '#FFFF99',
width: 3.5,
}),
}),
})
);
map.addLayer(
new ol.layer.Vector({
source: new ol.source.Vector({
features: [oneP],
}),
zindex: 52,
})
);
}
// 将方向标注放在线段中间
function direction_labeling_02(res, lineStringForl, coordis, vs, styles) {
for (let i = 0; i < vs.length; i++) {
let line = vs[i]['line'];
let start = line[0];
let end = line[1];
let array_coor = [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2];
let d = vs[i]['d'];
styles.push(
new ol.style.Style({
geometry: new ol.geom.Point(array_coor),
image: new ol.style.Icon({
src: webHome + '/common/images/arrow/arrow_t.png',
scale: 0.3,
rotateWithView: true,
rotation: -d,
}),
})
);
}
}
function calcD(start, end) {
let dx = end[0] - start[0];
let dy = end[1] - start[1];
let rotation = Math.atan2(dy, dx);
console.log('角度' + rotation);
return rotation;
}
function calcLineStringD(coordis) {
let n = coordis.length;
let vs = [];
for (let i = 0; i < n; i++) {
if (i + 1 < n) {
vs.push({
line: [coordis[i], coordis[i + 1]],
d: calcD(coordis[i], coordis[i + 1]),
});
}
}
return vs;
}
function addLine() {
let oneP = new ol.Feature({
geometry: new ol.geom.LineString([
[113.006943, 28.219305],
[113.009943, 28.219605],
// [113.010943, 28.220305],
]),
});
map.addLayer(
new ol.layer.Vector({
source: new ol.source.Vector({
features: [oneP],
}),
zindex: 22,
})
);
//oneP.set("desc", _desc);
oneP.setStyle(function (resolution) {
var lineStringForl = resolution.getGeometry();
var coordis = lineStringForl.getCoordinates();
var styles = [
new ol.style.Style({
stroke: new ol.style.Stroke({
lineDash:[10,10,10,10],
//lineDash:[20, 10, 40, 20],
//lineDash:[1,2,3,4,5,6],
color: 'green',
width: 8,
}),
}),
];
// 计算线段角度
let vs = calcLineStringD(coordis);
// direction_labeling_01(res, lineStringForl, coordis, vs, styles);
direction_labeling_02(100, lineStringForl, coordis, vs, styles);
return styles;
});
}
function clearDraw() {
drawSource.clear();
FancePoints = new Array();
}
function addInteractions() {
draw = new ol.interaction.Draw({
source: drawSource,
type: 'Polygon',
});
//map.removeInteraction(draw);
map.addInteraction(draw);
snap = new ol.interaction.Snap({ source: drawSource });
map.addInteraction(snap);
draw.on(
'drawstart',
function (evt) {
drawSource.clear();
},
this
);
draw.on(
'drawend',
function (evt) {
// set sketch
FancePoints = [];
var geom = evt.feature.getGeometry().getCoordinates()[0];
for (var k = 0; k < geom.length; k++) {
FancePoints[FancePoints.length] = { lon: geom[k][0], lat: geom[k][1] };
}
map.removeInteraction(draw);
showFance();
},
this
);
}
function showFance() {
var onePF = null;
var _cos = new Array();
for (var i = 0; i < FancePoints.length; i++) {
_cos[_cos.length] = [FancePoints[i].lon, FancePoints[i].lat];
}
onePF = new ol.Feature({
geometry: new ol.geom.Polygon([_cos]),
});
if (onePF != null) {
map.addLayer(
new ol.layer.Vector({
source: new ol.source.Vector({
features: [onePF],
}),
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(0, 255, 0, 0.3)',
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2,
}),
}),
zindex: 50,
})
);
}
}
function getDist() {
//let dis = new ol.Sphere(6378137);
//let _d=dis.haversineDistance([113.006943, 28.219305], [113.009943, 28.219605]);
alert(ol.sphere.getDistance([113.006943, 28.219305], [113.009943, 28.219605]));
}
/* ol.geom.Polygon.createRegularPolygonCurve = function(origin, radius, sides,r,angel) {
var rotation = 360 - r;
var angle = Math.PI * ((1/sides) - (1/2));
if(rotation) {
angle += (rotation / 180) * Math.PI;
}
var rotatedAngle, x, y;
var points = [];
for(var i=0; i<sides; ++i) {
var an = i*((360 - rotation)/360);
rotatedAngle = angle + (an * 2 * Math.PI / sides);
x = origin.x + (radius * Math.cos(rotatedAngle));
y = origin.y + (radius * Math.sin(rotatedAngle));
points.push([x, y]);
}
if(rotation!=0){
points.push([origin]);
}
//var ring = new ol.geom.LinearRing(points);
//ring.rotate(parseFloat(r)+90+parseFloat(angel),origin);
return new ol.geom.Polygon([points]);
};
function getRings (center, radius, startAngle, endAngle, pointNum) {
var sin;
var cos;
var x;
var y;
var angle;
var points = new Array();
points.push(center);
for (var i = 0; i <= pointNum; i++) {
angle = startAngle + (endAngle - startAngle) * i / pointNum;
sin = Math.sin(angle * Math.PI / 180);
cos = Math.cos(angle * Math.PI / 180);
x = center[0] + radius * sin;
y = center[1] + radius * cos;
points[i + 1] = [x, y];
}
var point = points;
point.push(center);
return new ol.geom.Polygon([point]);
}
function addRegularPolygon(){
let oneP = new ol.Feature({
geometry: getRings([113.005943, 28.219205],1000,30,180,100)
});
//oneP.set("desc", _desc);
oneP.setStyle(new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(0, 255, 0, 0.3)'
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
})
}));
// UserFeature["d_" + _data.eqpid] = oneP;
var mapLayers = new ol.layer.Vector({
source: new ol.source.Vector({
features: [oneP]
}),
zindex: 20
});
map.addLayer(mapLayers);
} */
/**
* 创建扇形
* @param [x,y] center 扇形中心点
* @param number randius 扇形半径 与中心点对应的坐标系单位
* @param number sAngle 扇形起始边与X轴正方向夹角°
* @param number angle 圆心角°(逆时针方向为正)
* @returns {ol.geom.Polygon}
* @constructor
*/
ol.geom.Sector = function (center, randius, sAngle, angle) {
sAngle = (360 - sAngle + 90) % 360;
var points = [];
points.push(center);
var ep = null;
for (var i = 0; i <= angle; ++i) {
var x = center[0] + randius * Math.cos(((sAngle + i) * Math.PI) / 180);
var y = center[1] + randius * Math.sin(((sAngle + i) * Math.PI) / 180);
points.push([x, y]);
}
points.push(center);
return new ol.geom.Polygon([points]);
};
/**
* _id:设备ID
* @param [x,y] _point 扇形中心点
* @param number _bj 扇形半径 m
* @param number sAngle 扇形起始边与X轴正方向夹角°
* @param number angle 圆心角°(逆时针方向为正)
* @returns {ol.geom.Polygon}
* @constructor
*/
function addRegularPolygon(_id, _point, _bj, sAngle, angle, _func) {
debugger;
let oneP = new ol.Feature({
geometry: new ol.geom.Sector(
_point,
_bj / map.getView().getProjection().getMetersPerUnit(),
sAngle,
angle
),
});
//oneP.set("desc", _desc);
oneP.setStyle(
new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(0, 255, 0, 0.3)',
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2,
}),
})
);
// UserFeature["d_" + _data.eqpid] = oneP;
var mapLayers = new ol.layer.Vector({
source: new ol.source.Vector({
features: [oneP],
}),
zindex: 20,
});
map.addLayer(mapLayers);
//map.addLayer(mapLayers);
//MarkList["tp_" + _id] = mapLayers;
//map.removeLayer(MapRadar[_id]);
//MapRadar[_id] = mapLayers;
//if (MapRadarShow) {
//map.addLayer(mapLayers);
//}
}
//备注:起点=设备角度+圆心角/2 40起点现在是写死的
function addRegularPolygonTest() {
addRegularPolygon('tt1pt', [113.006943, 28.219305], 1500, 40, 90);
}
//聚合
var dataSource = [
{
lat: 113.006943,
lon: 28.219305,
userName: '四方坪',
monthYear: 'ddddd',
code: '110',
waterUse: '14521',
},
{
lat: 113.006493,
lon: 28.209305,
userName: '四方坪',
monthYear: 'ddddd',
code: '110',
waterUse: '14521',
},
];
var features = new Array(dataSource.length);
for (var i = 0; i < dataSource.length; i++) {
// var coordinate = ol.proj.transform([lat[i], lon[i]], 'EPSG:4326', 'EPSG:3857');
// var coordinate = ol.proj.transform([lat[i], lon[i]], 'EPSG:4326', 'EPSG:4326');
var coordinate = [dataSource[i].lat, dataSource[i].lon];
coordinate.map(parseFloat);
// console.log("转换后经纬度:" + coordinate);
var attr = {
userName: dataSource[i].userName,
lat: dataSource[i].lat,
lon: dataSource[i].lon,
address: dataSource[i].monthYear,
code: dataSource[i].code,
phone: dataSource[i].waterUse,
};
features[i] = new ol.Feature({
geometry: new ol.geom.Point(coordinate),
attribute: attr,
});
}
var source = new ol.source.Vector({
features: features,
});
var clusterSource = new ol.source.Cluster({//矢量图层的数据源为聚合类型
distance: 40,//聚合距离
source: source,//聚合数据来源
});
maxFeatureCount = 0;
//加载聚合标注的矢量图层
var styleCache = {};
var layerVetor = new ol.layer.Vector({
source: clusterSource,
style: function (feature, resolution) {
var size = feature.get('features').length;
var style = styleCache[size];
if (!style) {
style = [
new ol.style.Style({
image: new ol.style.Icon(
/** @type {olx.style.IconOptions} */ ({
anchor: [0.5, 10],
anchorOrigin: 'top-right',
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
offsetOrigin: 'top-right',
offset: [0, 1], //偏移量设置
scale: 1.2, //图标缩放比例
opacity: 1, //透明度
src: webHome + '/common/images/arrow/arrow_b2.png', //图标的url
})
),
text: new ol.style.Text({
font: '28px Calibri,sans-serif',
text: size.toString(),
fill: new ol.style.Fill({
color: '#000',
border: 5,
width: 30,
}),
}),
}),
];
styleCache[size] = style;
}
return style;
},
});
map.addLayer(layerVetor);
function addEventListener() {}
//测距开始
// 已绘制的坐标集合
// //创建比例尺控件
// var scaleLineControl = new ol.control.ScaleLine({
// units: 'metric',
// target: 'scalebar',
// className: 'ol-scale-line'
// });
function measure() {
var drawCoordinateArr = []
//定义一个控制鼠标点击次数的变量
var count = 0;
var listener;
//创建一个当前要绘制的对象
var sketch;
//创建一个WGS84球体对象
//var wgs84Sphere = new ol.sphere(6378137);
//创建一个帮助提示框对象
var helpTooltipElement;
//创建一个帮助提示信息对象
var helpTooltip;
//创建一个测量提示框对象
var measureTooltipElement;
//创建一个测量提示信息对象
var measureTooltip;
//继续绘制多边形的提示信息
var continuePolygonMsg;
//继续绘制线段的提示信息
var continueLineMsg;
//帮助提示信息
var helpMsg;
//定义矢量数据源
var source = new ol.source.Vector();
//定义矢量图层
var vector = new ol.layer.Vector({
source: source,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255,255,255,0.2)',
}),
stroke: new ol.style.Stroke({
color: '#e21e0a',
width: 2,
}),
image: new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: '#ffcc33',
}),
}),
}),
});
sketch = new ol.Feature();
// continuePolygonMsg = 'Click to continue drawing the polygon';
// continueLineMsg = 'Click to continue drawing the line';
//将矢量图层添加到地图中
map.removeLayer(vector);
map.addLayer(vector);
//添加比例尺控件
// map.removeControl(scaleLineControl);
// map.addControl(scaleLineControl);
//鼠标移动触发的函数
var pointerMoveHandler = function (evt) {
//如果是平移地图则直接结束
if (evt.dragging) {
return;
}
//帮助提示信息
//helpMsg = 'Click to start drawing';
if (sketch) {
//获取绘图对象的几何要素
var geom = sketch.getGeometry();
//如果当前绘制的几何要素是多线段,则将绘制提示信息设置为多线段绘制提示信息
// if (geom instanceof ol.geom.Polygon) {
// helpMsg = continuePolygonMsg;
// } else if (geom instanceof ol.geom.LineString) {
// helpMsg = continueLineMsg;
// }
}
//设置帮助提示要素的内标签为帮助提示信息
// if (helpTooltipElement)
// helpTooltipElement.innerHTML = helpMsg;
//设置帮助提示信息的位置
// if (helpTooltip)
helpTooltip.setPosition(evt.coordinate);
//移除帮助提示要素的隐藏样式
// $(helpTooltipElement).removeClass('hidden');
removeClass(document.getElementsByClassName('tooltip')[0], 'hidden');
};
//触发pointermove事件
map.on('pointermove', pointerMoveHandler);
//当鼠标移除地图视图的时为帮助提示要素添加隐藏样式
document.querySelector('.ol-viewport').onmouseout = function () {
addClass(document.getElementsByClassName('tooltip')[0], 'hidden');
};
// 判断class有无
function hasClass(ele, cls) {
if (ele) {
cls = cls || '';
if (cls.replace(/\s/g, '').length == 0) return false; //当cls没有参数时返回false
return new RegExp(' ' + cls + ' ').test(' ' + ele.className + ' ');
}
}
//添加class
function addClass(ele, cls) {
if (!hasClass(ele, cls) && ele) {
ele.className = ele.className == '' ? cls : ele.className + ' ' + cls;
}
}
// 去除class
function removeClass(ele, cls) {
if (hasClass(ele, cls) && ele) {
var newClass = ' ' + ele.className.replace(/[\t\r\n]/g, '') + ' ';
while (newClass.indexOf(' ' + cls + ' ') >= 0) {
newClass = newClass.replace(' ' + cls + ' ', ' ');
}
ele.className = newClass.replace(/^\s+|\s+$/g, '');
}
}
//定义一个交互式绘图对象
var draw;
//添加交互式绘图对象的函数
function addInteraction() {
//创建一个交互式绘图对象
draw = new ol.interaction.Draw({
//绘制的数据源
source: source,
//绘制类型
type: 'LineString',
//样式
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255,255,255,0.2)',
}),
stroke: new ol.style.Stroke({
color: 'rgba(0,0,0,0.5)',
lineDash: [10, 10],
width: 2,
}),
image: new ol.style.Circle({
radius: 5,
stroke: new ol.style.Stroke({
color: 'rgba(0,0,0,0.7)',
}),
fill: new ol.style.Fill({
color: 'rgba(255,255,255,0.2)',
}),
}),
}),
});
//将交互绘图对象添加到地图中
map.addInteraction(draw);
//创建测量提示框
createMeasureTooltip();
//创建帮助提示框
createHelpTooltip();
//定义一个事件监听
//var listener;
//绘制开始事件
draw.on(
'drawstart',
function (evt) {
//$("#deletePoint-"+count).bind('click', deleteClick);
//document.removeEventListener('click', deleteClick);
count++;
//The feature being drawn.
sketch = evt.feature;
//提示框的坐标
var tooltipCoord = evt.coordinate;
//监听几何要素的change事件
//Increases the revision counter and dispatches a 'change' event.
listener = sketch.getGeometry().on('change', function (evt) {
//The event target.
//获取绘制的几何对象
var geom = evt.target;
//定义一个输出对象,用于记录面积和长度
var output;
if (geom instanceof ol.geom.Polygon) {
map.removeEventListener('singleclick');
map.removeEventListener('dblclick');
//输出多边形的面积
output = formatArea(geom);
//Return an interior point of the polygon.
//获取多变形内部点的坐标
tooltipCoord = geom.getInteriorPoint().getCoordinates();
} else if (geom instanceof ol.geom.LineString) {
//输出多线段的长度
output = formatLength(geom);
//Return the last coordinate of the geometry.
//获取多线段的最后一个点的坐标
tooltipCoord = geom.getLastCoordinate();
}
//设置测量提示框的内标签为最终输出结果
// if (measureTooltipElement)
measureTooltipElement.innerHTML = output;
//设置测量提示信息的位置坐标
// if (measureTooltip)
measureTooltip.setPosition(tooltipCoord);
//setToolStyle(measureTooltipElement);
});
// //地图单击事件
// map.on('singleclick', function (evt) {
// //设置测量提示信息的位置坐标,用来确定鼠标点击后测量提示框的位置
// // if (measureTooltip)
// measureTooltip.setPosition(evt.coordinate);
// //如果是第一次点击,则设置测量提示框的文本内容为起点
// if (count == 0 && measureTooltipElement) {
// measureTooltipElement.innerHTML = '起点';
// }
// //根据鼠标点击位置生成一个点
// var point = new ol.geom.Point(evt.coordinate);
// //将该点要素添加到矢量数据源中
// source.addFeature(new ol.Feature(point));
// //更改测量提示框的样式,使测量提示框可见
// measureTooltipElement.className = 'tooltip tooltip-static';
// //创建测量提示框
// createMeasureTooltip();
// //点击次数增加
// count++;
// });
// //地图双击事件
// map.on('dblclick', function (evt) {
// //根据
// var point = new ol.geom.Point(evt.coordinate);
// source.addFeature(new ol.Feature(point));
// });
},
this
);
//绘制结束事件
draw.on(
'drawend',
function (evt) {
//count = 0;
// //设置测量提示框的样式
// measureTooltipElement.className = 'tooltip tooltip-static';
// //Set the offset for this overlay.
// //设置偏移量
// measureTooltip.setOffset([0, -7]);
// //清空绘制要素
// sketch = null;
// //清空测量提示要素
// measureTooltipElement = null;
// //创建测量提示框
// createMeasureTooltip();
// //Removes an event listener using the key returned by on() or once().
// //移除事件监听
ol.Observable.unByKey(listener);
// //移除地图单击事件
// map.removeEventListener('singleclick');
const coordinates = evt.feature.getGeometry().getCoordinates()
evt.feature.set('tempdata', count);
drawCoordinateArr.push(coordinates);
drawPoint(coordinates);
$("#deletePoint-"+count).bind('click', deleteClick);
clearDraws();
},
this
);
}
function drawPoint (coordinates) {
const tempArr = []
for (let i = 0; i < coordinates.length; i++) {
tempArr.push(coordinates[i])
if (i === 0) {
createDom(coordinates[i], '起点', i, coordinates, count)
} else {
createDom(coordinates[i], formatLength(new ol.geom.LineString(tempArr)), i, coordinates, count)
}
}
}
// 绘制之后放置测量内容
function createDom (point, inner, i, coordinates, count) {
console.log(point, inner, i, coordinates, count)
// 设置测量提示信息的位置坐标,用来确定鼠标点击后测量提示框的位置
measureTooltip.setPosition(point);
measureTooltipElement.innerHTML = inner +
// `<img class="deletePoint" id="deletePoint-${lengthMeasureCount}-${i}" tempimgdata="${lengthMeasureCount}" src="${deletePoint}" style="width: 15px;padding-left: 5px;" />` +
// (i === coordinates.length - 1 ? `<img class="deleteLine" id="deleteLine${lengthMeasureCount}" tempimgdata="${lengthMeasureCount}" src="${deleteLineArea}" style="width: 20px;padding-left: 5px;" />` : '')
`<img class="deletePoint" id="deletePoint-${count}" tempimgdata="${count}" src="/yyyzweb/common/images/yuntai/up_icon.png" style="width: 15px;padding-left: 5px;" />`;
// (i === coordinates.length - 1 ? `<img class="deleteLine" id="deleteLine${count}" tempimgdata="${count}" src="/yyyzweb/common/images/yuntai/up_icon.png" style="width: 20px;padding-left: 5px;" />` : '');
measureTooltipElement.parentNode.style.zIndex = i;
measureTooltipElement.className = 'tooltip tooltip-static';
// 创建测量提示框
if (i === coordinates.length - 1) {
createMeasureTooltip(count, true);
} else {
createMeasureTooltip('', true);
}
// 给所有测量提示框设置样式
// document.querySelectorAll('.tooltip.tooltip-static').forEach(n => {
// setToolStyle(n);
// })
// setToolStyle(measureTooltipElement)
// 根据鼠标点击位置生成一个点
const pointLine = new ol.geom.Point(coordinates[i]);
let onePF = null;
onePF = new ol.Feature({
geometry: pointLine
});
// 将该点要素添加到矢量数据源中
const tempLayer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [onePF]
}),
//style,
tempdata: count,
updateWhileAnimating: true
})
map.addLayer(tempLayer);
}
function clearDraws () {
measureTooltipElement.innerHTML = ('总长:') + measureTooltipElement.innerHTML;
measureTooltipElement.className = 'ol-tooltip ol-tooltip-static measureNum';
setToolStyle(measureTooltipElement);
measureTooltip.setOffset([0, -7]);
// unset sketch
sketch = null
// unset tooltip so that a new one can be created
measureTooltipElement = null;
createMeasureTooltip();
//移除事件监听
ol.Observable.unByKey(listener);
map.un('pointermove', pointerMoveHandler);
map.removeInteraction(draw);
helpTooltipElement.classList.add('hidden');
}
// 点击测距的删除
function deleteClick (e) {
const target = e.target;
const eIndex = target.getAttribute('tempimgdata');
deleteLayers(eIndex, target);
drawCoordinateArr[parseInt(eIndex) - 1] = [];
// if (target.className === 'deleteLine') {
// deleteLayers(eIndex);
// drawCoordinateArr[parseInt(eIndex) - 1] = [];
// } else if (target.className === 'deletePoint') {
// deleteLayers(eIndex, target);
// }
}
// 删除某个点之后重新测量距离
function drawFresh (eIndex) {
console.log(eIndex)
const coordinates = drawCoordinateArr[parseInt(eIndex) - 1];
const lineString = new LineString(coordinates);
// 将该点要素添加到矢量数据源中
const tempLayer = new ol.layer.Vector({
source: new new ol.source.Vector({
features: [
new Feature({
geometry: lineString
})
]
}),
style,
tempdata: eIndex,
updateWhileAnimating: true
})
map.addLayer(tempLayer);
const tempArr = []
for (let i = 0; i < coordinates.length; i++) {
tempArr.push(coordinates[i])
if (i === 0) {
createDom(coordinates[i], '起点', i, coordinates, eIndex)
} else {
createDom(coordinates[i], formatLength(mapView, new LineString(tempArr)), i, coordinates, eIndex)
}
}
}
// 删除当前点击的图层
function deleteLayers (eIndex, target) {
const overlaysArr = map.getOverlays().getArray();
const layersArr = map.getLayers().getArray();
// 先把需要删除的Overlays存在一个数组中
// 如果不储存直接去删除Overlays就会出现需要删除却识别不到的图层
const deleteOverlayArr = [];
const deleteLayerArr = [];
for (let i = 0; i < overlaysArr.length; i++) {
const lastChild = overlaysArr[i].values_.element?.lastChild;
if (lastChild?.id && lastChild?.getAttribute('tempimgdata') === eIndex) {
deleteOverlayArr.push(overlaysArr[i]);
}
}
map.getLayers().getArray().forEach((n, i) => {
if (n.getSource() && n instanceof ol.layer.Vector && n.getSource().getFeatures()[0] && n.getSource().getFeatures()[0].get('tempdata') && n.getSource().getFeatures()[0].get('tempdata').toString() === eIndex) {
deleteLayerArr.push(n);
}
})
for (let i = 0; i < layersArr.length; i++) {
if (layersArr[i].values_.tempdata && layersArr[i].values_.tempdata.toString() === eIndex) {
deleteLayerArr.push(layersArr[i])
}
}
// 单独处理需要删除的Overlays和Layers
deleteOverlayArr.forEach(n => map.removeOverlay(n));
deleteLayerArr.forEach(n => map.removeLayer(n));
// 删除之后重新画
if (target) {
const index = target.id.split('-');
drawCoordinateArr[parseInt(index[1]) - 1].splice(parseInt(index[2]), 1);
if (drawCoordinateArr[parseInt(index[1]) - 1].length > 1){
drawFresh(index[1]);
}
}
}
function setToolStyle(measureTooltipElement){
// 这里可以根据你需要的测量提示框的样式做修改
measureTooltipElement.style.color = '#C3C5C9'
measureTooltipElement.style.padding = '0 10px'
measureTooltipElement.style.height = '25px'
measureTooltipElement.style.lineHeight = '20px'
measureTooltipElement.style.background = '#1A1A1B'
measureTooltipElement.style.fontSize = '15px'
measureTooltipElement.style.fontWeight = '400'
}
//创建帮助提示框
function createHelpTooltip() {
//如果已经存在帮助提示框则移除
if (helpTooltipElement) {
helpTooltipElement.parentNode.removeChild(helpTooltipElement);
}
//创建帮助提示要素的div
if (!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() {
//创建测量提示框的div
// if (!measureTooltipElement)
measureTooltipElement = document.createElement('div');
measureTooltipElement.setAttribute('id', 'lengthLabel');
//设置测量提示要素的样式
measureTooltipElement.className = 'tooltip tooltip-measure';
//创建一个测量提示的覆盖标注
measureTooltip = new ol.Overlay({
element: measureTooltipElement,
offset: [0, -15],
positioning: 'bottom-center',
});
//将测量提示的覆盖标注添加到地图中
map.addOverlay(measureTooltip);
}
//格式化测量长度
var formatLength = function (line) {
//定义长度变量
var length;
//获取坐标串
var coordinates = line.getCoordinates();
//初始长度为0
length = 0;
//获取源数据的坐标系
var sourceProj = map.getView().getProjection();
//进行点的坐标转换
for (var i = 0; i < coordinates.length - 1; i++) {
//第一个点
var c1 = ol.proj.transform(coordinates[i], sourceProj, 'EPSG:4326');
//第二个点
var c2 = ol.proj.transform(coordinates[i + 1], sourceProj, 'EPSG:4326');
//获取转换后的球面距离
//Returns the distance from c1 to c2 using the haversine formula.
length += ol.sphere.getDistance(c1, c2);
}
//计算平面距离
//length = Math.round(line.getLength() * 100) / 100;
//定义输出变量
var output;
//如果长度大于1000则使用km单位否则使用m单位
if (length > 100) {
output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km'; //换算成KM单位
} else {
output = Math.round(length * 100) / 100 + ' ' + 'm'; //m为单位
}
return output;
};
//格式化测量面积
var formatArea = function (polygon) {
//定义面积变量
var area;
//获取初始坐标系
var sourceProj = map.getView().getProjection();
var geom = polygon.clone().transform(sourceProj, 'EPSG:4326');
//获取多边形的坐标系
var coordinates = geom.getLinearRing(0).getCoordinates();
//获取球面面积
area = Math.abs(ol.sphere.geodesicArea(coordinates));
//获取平面面积
//area = polygon.getArea();
// }
//定义输出变量
var output;
//当面积大于10000时转换为平方千米否则为平方米
if (area > 1000) {
output = Math.round((area / 1000000) * 100) / 100 + ' ' + '公里<sup>2</sup>';
} else {
output = Math.round(area * 100) / 100 + ' ' + 'm<sup>2</sup>';
}
return output;
};
//添加交互绘图对象
addInteraction();
}
// 清除提示对象
function clear() {
source.clear();
map.getOverlays().clear();
map.removeLayer(vector);
map.removeControl(scaleLineControl);
}
map.measure = measure;
map.clear = clear;
// function measure(){
// /**
// * Currently drawn feature.
// * @type {module:ol/Feature~Feature}
// */
// var sketch;
// /**
// * The help tooltip element.
// * @type {Element}
// */
// var helpTooltipElement;
// /**
// * Overlay to show the help messages.
// * @type {module:ol/Overlay}
// */
// var helpTooltip;
// /**
// * The measure tooltip element.
// * @type {Element}
// */
// var measureTooltipElement;
// /**
// * Overlay to show the measurement.
// * @type {module:ol/Overlay}
// */
// var measureTooltip;
// /**
// * Message to show when the user is drawing a polygon.
// * @type {string}
// */
// var continuePolygonMsg = '继续点击绘制多边形';
// /**
// * Message to show when the user is drawing a line.
// * @type {string}
// */
// var continueLineMsg = '继续点击绘制线';
// createMeasureTooltip();
// createHelpTooltip();
// /**
// * Handle pointer move.
// * @param {module:ol/MapBrowserEvent~MapBrowserEvent} evt The event.
// */
// var pointerMoveHandler = function (evt) {
// if (evt.dragging) {
// return;
// }
// /** @type {string} */
// var helpMsg = '请点击开始绘制';
// if (sketch) {
// var geom = (sketch.getGeometry());
// helpMsg = continueLineMsg;
// // if (geom instanceof ol.geom.Polygon) {
// // helpMsg = continuePolygonMsg;
// // } else if (geom instanceof ol.geom.LineString) {
// // helpMsg = continueLineMsg;
// // }
// }
// helpTooltipElement.innerHTML = helpMsg;
// helpTooltip.setPosition(evt.coordinate);
// helpTooltipElement.classList.remove('hidden');
// };
// map.on('pointermove', pointerMoveHandler);
// map.getViewport().addEventListener('mouseout', function () {
// helpTooltipElement.classList.add('hidden');
// });
// var draw;
// var formatLength = function (line) {
// var length = getLength(line);
// var output;
// if (length > 100) {
// output = (Math.round(length / 1000 * 100) / 100) +
// ' ' + 'km';
// } else {
// output = (Math.round(length * 100) / 100) +
// ' ' + 'm';
// }
// return output;
// };
// var formatArea = function (polygon) {
// var area = getArea(polygon);
// var output;
// if (area > 10000) {
// output = (Math.round(area / 1000000 * 100) / 100) +
// ' ' + 'km<sup>2</sup>';
// } else {
// output = (Math.round(area * 100) / 100) +
// ' ' + 'm<sup>2</sup>';
// }
// return output;
// };
// // var source;
// // // var layer ;
// // // 获取存放feature的vectorlayer层。map初始化的时候可以添加好了
// // for(let layerTmp of map.getLayers().getArray()){
// // if(layerTmp.get("name")=="feature"){
// // // layer = layerTmp;
// // // layerTmp.setSource(null)
// // source= layerTmp.getSource();
// // }
// // }
// function addInteraction() {
// var type ='LineString';
// draw = new ol.interaction.Draw({
// source: drawSource,
// 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: 'rgba(0, 0, 0, 0.5)',
// lineDash: [10, 10],
// width: 2
// }),
// image: new ol.style.Circle({
// radius: 5,
// stroke: new ol.style.Stroke({
// color: 'rgba(0, 0, 0, 0.7)'
// }),
// fill: new ol.style.Fill({
// color: 'rgba(255, 255, 255, 0.2)'
// })
// })
// })
// });
// map.addInteraction(draw);
// var listener;
// draw.on('drawstart',
// function (evt) {
// // set sketch
// sketch = evt.feature;
// /** @type {module:ol/coordinate~Coordinate|undefined} */
// var tooltipCoord = evt.coordinate;
// listener = sketch.getGeometry().on('change', function (evt) {
// var geom = evt.target;
// var output;
// output = formatLength(geom);
// tooltipCoord = geom.getLastCoordinate();
// // if (geom instanceof ol.geom.Polygon) {
// // output = formatArea(geom);
// // tooltipCoord = geom.getInteriorPoint().getCoordinates();
// // } else if (geom instanceof ol.geom.LineString) {
// // output = formatLength(geom);
// // tooltipCoord = geom.getLastCoordinate();
// // }
// measureTooltipElement.innerHTML = output;
// measureTooltip.setPosition(tooltipCoord);
// });
// }, this);
// draw.on('drawend',
// function () {
// measureTooltipElement.className = 'tooltip tooltip-static';
// measureTooltip.setOffset([0, -7]);
// // unset sketch
// sketch = null;
// // unset tooltip so that a new one can be created
// measureTooltipElement = null;
// createMeasureTooltip();
// unByKey(listener);
// map.un('pointermove', pointerMoveHandler);
// map.removeInteraction(draw);
// helpTooltipElement.classList.add('hidden');
// }, this);
// }
// function createHelpTooltip() {
// if (helpTooltipElement) {
// 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);
// }
// // 量测调用
// addInteraction();
// }
</script>
</body>
</html>