yarn add ol
import MouseWheelZoom from "ol/interaction/MouseWheelZoom";
import { MousePosition } from 'ol/control'
import { createStringXY } from 'ol/coordinate'
import { Map, View } from "ol";//地图,视图
import OSM from "ol/source/OSM"; //可以理解为数据源,就是一张图片
import TileLayer from "ol/layer/Tile"; //可以理解为图层
import { fromLonLat } from "ol/proj";//将坐标从经度/纬度转换为不同的投影。
绘制功能
//绘制对象
source: that.drawSource, //绘制层数据源,勾绘的要素属于的数据集
type: "Polygon", //绘制的类型,这里绘制一个多边形,也可以是POINT(点)、LINE_STRING(线)、CIRCLE(圆)
//设置一些样式
style: new Style({
fill: new Fill({
color: "rgba(0,0,255,0.2)",
}),
stroke: new Stroke({
color: "#0000ff",
width: 2,
}),
image: new Circle({
radius: 7,
fill: new Fill({
color: "#0000ff",
}),
}),
}),
});
this.map.addInteraction(draw); //添加交互
// 测距 (下面有测距和侧面积的集成)
var map = null
var helpTooltipElement = null
var feature = null;
var helpTooltip = null;
var draw = null;
var measureTooltipElement = null;
var measureTooltip = null;
var listener = null;
var mapMouseMove = null;
import VectorSource from "ol/source/Vector";
import { Vector as VectorLayer } from "ol/layer";
import { Circle,Style,Stroke,Fill } from "ol/style";
import Overlay from 'ol/Overlay';
import { Draw,DoubleClickZoom } from "ol/interaction";
import { getArea, getLength } from 'ol/sphere';
import { unByKey } from 'ol/Observable';
distance() {
let source = new VectorSource()
const layer = new VectorLayer({
source: source,
style: new Style({
fill: new Fill({
color: 'rgba(255, 255, 255, 0.2)',
}),
stroke: new Stroke({
color: '#ffcc33',
width: 4,
}),
image: new Circle({
radius: 7,
fill: new Fill({
color: '#ffcc33',
}),
}),
}),
});
mapMouseMove = this.$map.on('pointermove', (ev) => {
let helpMsg = '点击开始测量'
if (feature) {
helpMsg = '双击结束测量'
}
helpTooltipElement.innerHTML = helpMsg;
helpTooltip.setPosition(ev.coordinate);
helpTooltipElement.classList.remove('hidden')
})
this.$map.getViewport().addEventListener('mouseout', function () {
helpTooltipElement.classList.add('hidden');
});
draw = new Draw({
source,
type: 'LineString',
style: new Style({
fill: new Fill({
color: 'rgba(255, 255, 255, 0.2)',
}),
stroke: new Stroke({
color: 'rgba(0, 0, 0, 0.5)',
lineDash: [10, 10],
width: 4,
}),
image: new Circle({
radius: 5,
stroke: new Stroke({
color: 'rgba(0, 0, 0, 0.7)',
}),
fill: new Fill({
color: 'rgba(255, 255, 255, 0.2)',
}),
}),
}),
});
// 开始坚挺绘制
draw.on('drawstart', (evt) => {
feature = evt.feature;
let tooltipCoord = evt.coordinate;
listener = feature.getGeometry().on('change', function (evt) {
const geom = evt.target;
let output = formatLength(geom);
tooltipCoord = geom.getLastCoordinate();
measureTooltipElement.innerHTML = output;
measureTooltip.setPosition(tooltipCoord);
});
});
// 双击绘制完成
draw.on('drawend', () => {
measureTooltipElement.className = 'ol-tooltip ol-tooltip-static';
measureTooltip.setOffset([0, -7]);
feature = null;
measureTooltipElement = null;
this.createMeasureTooltip();
unByKey(listener);
this.cancal()
});
// 格式化长度
const formatLength = function (line) {
const length = getLength(line);
let output;
if (length > 100) {
output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km';
} else {
output = Math.round(length * 100) / 100 + ' ' + 'm';
}
return output;
};
this.createHelpTooltip()
this.createMeasureTooltip()
this.$map.addLayer(layer)
this.drawLayers.push(layer)
this.$map.addInteraction(draw);
},
// 取消绘制
cancal() {
// for(let i = 0 ; i< this.drawLayers.length; i++) {
// this.$map.removeLayer(this.drawLayers[i])
// }
// for (let i = 0; i < this.drawElements.length; i++) {
// this.$map.removeOverlay(this.drawElements[i])
// }
// this.drawLayers = []
// this.drawElements = []
helpTooltipElement.innerHTML=''
this.$map.removeInteraction(draw)
unByKey(mapMouseMove);
},
createMeasureTooltip() {
if (measureTooltipElement) {
measureTooltipElement.parentNode.removeChild(measureTooltipElement);
}
measureTooltipElement = document.createElement('div');
measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure';
measureTooltip = new Overlay({
element: measureTooltipElement,
offset: [0, -15],
positioning: 'bottom-center',
stopEvent: false,
insertFirst: false,
});
this.drawElements.push(measureTooltip)
this.$map.addOverlay(measureTooltip);
},
createHelpTooltip() {
if (helpTooltipElement) {
helpTooltipElement.parentNode.removeChild(helpTooltipElement);
}
helpTooltipElement = document.createElement('div');
helpTooltipElement.className = 'ol-tooltip hidden';
helpTooltip = new Overlay({
element: helpTooltipElement,
offset: [15, 0],
positioning: 'center-left',
});
this.$map.addOverlay(helpTooltip);
},
var view = this.$map.getView();
// 设置地图等级
view.setZoom(Number(this.number) +1);
this.$map.render();
// 设置地图中心,将地图移动到中心点
view.setCenter([,]);
this.$map.render();
//获取鼠标在地图上的坐标点
<div id='mousePosition'></div>
this.mousePositionControl = new MousePosition({
coordinateFormat: function (e) { // 这里格式化成 X: ** Y: **
let stringifyFunc = createStringXY(4)
let str = stringifyFunc(e)
return str.split(',')[0] + ' ' + str.split(',')[1]
},
projection: 'EPSG:4326', // 和地图坐标系保持一致
className: 'custom-mouse-position', // css类名
target: document.getElementById('mousePosition') // 显示位置鼠标坐标位置DOM
})
// 添加控制控件到地图上即可
this.$map.addControl(this.mousePositionControl)
js文件
Measure.measure(this.$map, 'area'); //测面积
Measure.measure(this.$map, ''); //测距离
import Draw from 'ol/interaction/Draw'
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import Point from "ol/geom/Point";
import {
unByKey
} from 'ol/Observable.js';
import Overlay from 'ol/Overlay';
import {Feature } from "ol";
// import {
// getArea,
// getLength
// } from 'ol/sphere.js';
import {getLength} from 'ol/sphere';
import {getArea} from 'ol/sphere';
import LineString from 'ol/geom/LineString';
import Polygon from 'ol/geom/Polygon';
import {
Circle as CircleStyle,
Fill,
Stroke,
Style
} from 'ol/style.js';
export default{
measure(map, measureType) {
var source = new VectorSource();
var vector = new VectorLayer({
id:'lineAndArea',
source: source,
style: new Style({
fill: new Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new Stroke({
color: 'red',
width: 2
}),
image: new CircleStyle({
radius: 7,
fill: new Fill({
color: '#ffcc33'
})
})
}),
zIndex:16
});
map.addLayer(vector)
/**
* 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());
if (geom instanceof Polygon) {
helpMsg = continuePolygonMsg;
} else if (geom instanceof 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 sourceProj = map.getView().getProjection();
//ol/sphere里有getLength()和getArea()用来测量距离和区域面积,默认的投影坐标系是EPSG:3857, 其中有个options的参数,可以设置投影坐标系
var length = getLength(line, {projection: sourceProj});
//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 sourceProj = map.getView().getProjection();
var area = getArea(polygon, {projection: sourceProj})
//var area = getArea(polygon);
//console.info(area)
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 = (measureType == 'area' ? 'Polygon' : 'LineString');
draw = new Draw({
source: source,
type: type,
style: new Style({
fill: new Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new Stroke({
color: 'rgba(0, 0, 0, 0.5)',
lineDash: [10, 10],
width: 2
}),
image: new CircleStyle({
radius: 5,
stroke: new Stroke({
color: 'rgba(0, 0, 0, 0.7)'
}),
fill: new 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;
if (geom instanceof Polygon) {
output = formatArea(geom);
tooltipCoord = geom.getInteriorPoint().getCoordinates();
} else if (geom instanceof LineString) {
output = formatLength(geom);
tooltipCoord = geom.getLastCoordinate();
}
measureTooltipElement.innerHTML = output;
measureTooltip.setPosition(tooltipCoord);
});
//地图双击事件
map.on('dblclick', function (evt) {
var point = new Point(evt.coordinate);
source.addFeature(new Feature(point));
idea = false;
// alert(idea)
});
}, 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 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 Overlay({
element: measureTooltipElement,
offset: [0, -15],
positioning: 'bottom-center'
});
map.addOverlay(measureTooltip);
}
// 量测调用
addInteraction();
$(document).keyup(function (event) {
if (event.keyCode == 27)
draw.abortDrawing();
else if (event.keyCode == 90 && event.ctrlKey) {
console.log(draw);
if (typeSelect.value== 'Circle')
draw.abortDrawing();
else
draw.removeLastPoint()
}
})
//绘制结束
}
}