tool-draw.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. import * as ol from 'ol'
  2. import * as style from 'ol/style'
  3. import * as layer from 'ol/layer'
  4. import * as source from 'ol/source'
  5. import * as interaction from 'ol/interaction'
  6. import Modify from "ol/interaction/Modify"
  7. import {createBox} from "ol/interaction/Draw"
  8. import * as sphere from "ol/sphere";
  9. import {unByKey} from "ol/Observable";
  10. import {isValue} from "@/utils/util";
  11. // @ts-ignore
  12. import PointIcon from "@/assets/images/gis-layout/gis-layout-tools_tool-bz_icon.png"
  13. import {v4} from "uuid";
  14. const globalLineDash = [
  15. [0, 0], //实线
  16. [15, 15], //长虚线
  17. [5, 5] //虚线
  18. ]
  19. const layerFlag = ['layerName', 'toolDrawViewsLayer']
  20. const drawFlag = ['interactionName', 'toolDrawInteraction']
  21. const modifyFlag = ['interactionName', 'toolModifyInteraction']
  22. const baseDrawConfig = {
  23. // 样式字段
  24. text: null, // 要素上显示的文字,默认无文字
  25. pointIcon: PointIcon, // Point的图标
  26. pointScale: 1, // Point的缩放,默认1
  27. pointOffset: [0, 24], // Point的偏移量,默认[0, 0]
  28. rectangle: false,
  29. lineColor: '#2860F1', // LineString的线段颜色,默认蓝色
  30. lineWidth: 2, // LineString的线段宽度,默认1
  31. lineType: 0, // LineString的线段类型索引,默认0,实线,取globalLineDash数组索引
  32. lineDash: null, // LineString的线段类型,默认null,优先级比lineType高
  33. polyColor: 'rgba(20, 129, 241, 0.1)', // Polygon的填充色,默认蓝色
  34. polyBorderColor: '#2860F1', // Polygon的边框颜色,默认蓝色
  35. polyBorderWidth: 2, // Polygon的边框宽度,默认1
  36. polyBorderType: 0, // Polygon的边框类型索引,默认0,实线,取globalLineDash数组索引
  37. polyBorderDash: null, // Polygon的边框类型,默认null,优先级比polyBorderType高
  38. // 业务字段
  39. show: false, // 标绘样式选项是否显示
  40. featureType: 'Point', // 标绘的要素类型
  41. isPoint: false, // 是否可以标绘点
  42. isLineString: false, // 是否可以标绘线
  43. isPolygon: false, // 是否可以标绘面
  44. showPosition: false, // 是否显示经纬度输入框
  45. refreshStyleFunc: () => {}, // 刷新标绘样式方法
  46. }
  47. export const getBaseDrawConfig = () => {
  48. return JSON.parse(JSON.stringify(baseDrawConfig))
  49. }
  50. /**
  51. *
  52. * @param map
  53. * @param arr 要标绘的数组,每个对象的数据在要素中保存的属性为 'val'
  54. * @param arr > wkt:wkt格式坐标
  55. * @param arr > styles:要素的样式,优先级最高
  56. * @param arr > text:styles为空的时候,要素上显示的文字,默认无文字
  57. * @param arr > textOffsetY:styles为空的时候,要素上显示的文字Y轴偏移量,默认Point-30,其他0
  58. * @param arr > pointIcon:styles为空的时候,Point的图标,默认圆形
  59. * @param arr > pointScale:styles为空的时候,Point的缩放,默认1
  60. * @param arr > pointOffset:styles为空的时候,Point的偏移量,默认[0, 0]
  61. * @param arr > lineColor:styles为空的时候,LineString的线段颜色,默认蓝色
  62. * @param arr > lineWidth:styles为空的时候,LineString的线段宽度,默认1
  63. * @param arr > lineType:styles为空的时候,LineString的线段类型索引,默认0,实线,取globalLineDash数组索引
  64. * @param arr > lineDash:styles为空的时候,LineString的线段类型,默认null,优先级比lineType高
  65. * @param arr > polyColor:styles为空的时候,Polygon的填充色,默认蓝色
  66. * @param arr > polyBorderColor:styles为空的时候,Polygon的边框颜色,默认蓝色
  67. * @param arr > polyBorderWidth:styles为空的时候,Polygon的边框宽度,默认1
  68. * @param arr > polyBorderType:styles为空的时候,Polygon的边框类型索引,默认0,实线,取globalLineDash数组索引
  69. * @param arr > polyBorderDash:styles为空的时候,Polygon的边框类型,默认null,优先级比polyBorderType高
  70. */
  71. let toolDrawTooltipElement;
  72. let toolDrawHelpTooltipElement;
  73. export const draw = (map, obj) => {
  74. return new Promise((resolve => {
  75. if (!isValue(obj.textOffsetY)) {
  76. obj.textOffsetY = (obj.featureType === 'Point' ? -30 : 0)
  77. }
  78. let commonStyle = (showText, featureType = undefined) => {
  79. if ((featureType ?? obj.featureType) === 'Point') {
  80. return new style.Style({
  81. image: obj.pointIcon ? new style.Icon({
  82. src: obj.pointIcon,
  83. scale: obj.pointScale,
  84. displacement: obj.pointOffset
  85. }) : new style.Circle({
  86. radius: 10,
  87. fill: new style.Fill({
  88. color: '#e810dd',
  89. }),
  90. scale: obj.pointScale,
  91. displacement: obj.pointOffset
  92. }),
  93. text: (showText && obj.text) ? new style.Text({
  94. font: "16px bold 微软雅黑",
  95. text: obj.text,
  96. fill: new style.Fill({
  97. color: '#ffffff'
  98. }),
  99. stroke: new style.Stroke({
  100. color: '#D26CDB',
  101. width: 2
  102. }),
  103. offsetY: obj.textOffsetY,
  104. }) : undefined,
  105. })
  106. } else if ((featureType ?? obj.featureType) === 'LineString') {
  107. return new style.Style({
  108. stroke: new style.Stroke({
  109. color: obj.lineColor,
  110. width: obj.lineWidth,
  111. lineDash: obj.lineDash ?? globalLineDash[Number(obj.lineType)]
  112. }),
  113. text: (showText && obj.text) ? new style.Text({
  114. font: "16px bold 微软雅黑",
  115. text: obj.text,
  116. fill: new style.Fill({
  117. color: '#ffffff'
  118. }),
  119. stroke: new style.Stroke({
  120. color: '#D26CDB',
  121. width: 2
  122. }),
  123. offsetY: obj.textOffsetY,
  124. }) : undefined,
  125. })
  126. } else if ((featureType ?? obj.featureType) === 'Polygon' || (featureType ?? obj.featureType) === 'Circle') {
  127. return new style.Style({
  128. stroke: new style.Stroke({
  129. color: obj.polyBorderColor,
  130. width: obj.polyBorderWidth,
  131. lineDash: obj.polyBorderDash ?? globalLineDash[Number(obj.polyBorderType)]
  132. }),
  133. fill: new style.Fill({
  134. color: obj.polyColor,
  135. }),
  136. text: (showText && obj.text) ? new style.Text({
  137. font: "16px bold 微软雅黑",
  138. text: obj.text,
  139. fill: new style.Fill({
  140. color: '#ffffff'
  141. }),
  142. stroke: new style.Stroke({
  143. color: '#D26CDB',
  144. width: 2
  145. }),
  146. offsetY: obj.textOffsetY,
  147. }) : undefined,
  148. })
  149. }
  150. }
  151. const reset = () => {
  152. const oldLayer = map.getLayers().getArray().filter(v => v.get(layerFlag[0]) === layerFlag[1])
  153. if (oldLayer) {
  154. map.removeLayer(oldLayer[0])
  155. }
  156. const oldDraw = map.getInteractions().getArray().filter(v => v.get(drawFlag[0]) === drawFlag[1])
  157. if (oldDraw) {
  158. map.removeInteraction(oldDraw[0])
  159. }
  160. const oldModify = map.getInteractions().getArray().filter(v => v.get(modifyFlag[0]) === modifyFlag[1])
  161. if (oldModify) {
  162. map.removeInteraction(oldModify[0])
  163. }
  164. }
  165. if (!toolDrawTooltipElement) {
  166. // reset()
  167. let _source
  168. const realLayer = map.getLayers().getArray().filter(v => v.get(layerFlag[0]) === layerFlag[1])
  169. if (realLayer[0]) {
  170. _source = realLayer[0].getSource()
  171. } else {
  172. _source = new source.Vector(); //图层数据源
  173. const _vector = new layer.Vector({
  174. zIndex: 9999,
  175. source: _source,
  176. style: (feat: any) => {
  177. feat.setStyle(commonStyle(true, feat.getGeometry().getType()))
  178. },
  179. });
  180. _vector.set(layerFlag[0], layerFlag[1])
  181. map.addLayer(_vector);
  182. }
  183. const modifyInteraction = new Modify({
  184. source: _source,
  185. });
  186. modifyInteraction.set(modifyFlag[0], modifyFlag[1])
  187. map.addInteraction(modifyInteraction)
  188. modifyInteraction.on('modifyend', evt => {
  189. try {
  190. const feat = evt.features.item(0)
  191. } catch {
  192. }
  193. })
  194. if (!obj.wkt) {
  195. let sketch;
  196. let helpTooltip;
  197. let measureTooltip;
  198. let continueMsg = '双击结束标绘';
  199. const geodesicCheckbox = true;//测地学方式对象
  200. const createMeasureTooltip = () => {
  201. const id = 'toolDrawTooltipElementId'
  202. if (toolDrawTooltipElement) {
  203. map.removeOverlay(map.getOverlayById(id))
  204. toolDrawTooltipElement.parentNode.removeChild(toolDrawTooltipElement);
  205. }
  206. toolDrawTooltipElement = document.createElement('div');
  207. toolDrawTooltipElement.className = 'tooltip tooltip-measure';
  208. measureTooltip = new ol.Overlay({
  209. id,
  210. element: toolDrawTooltipElement,
  211. offset: [0, -15],
  212. positioning: 'bottom-center'
  213. });
  214. map.addOverlay(measureTooltip);
  215. }
  216. const createHelpTooltip = () => {
  217. const id = 'toolDrawHelpTooltipElementId'
  218. if (toolDrawHelpTooltipElement) {
  219. map.removeOverlay(map.getOverlayById(id))
  220. toolDrawHelpTooltipElement.parentNode.removeChild(toolDrawHelpTooltipElement);
  221. }
  222. toolDrawHelpTooltipElement = document.createElement('div');
  223. toolDrawHelpTooltipElement.className = 'tooltip hidden';
  224. helpTooltip = new ol.Overlay({
  225. id,
  226. element: toolDrawHelpTooltipElement,
  227. offset: [15, 0],
  228. positioning: 'center-left'
  229. });
  230. map.addOverlay(helpTooltip);
  231. }
  232. const formatLength = (line) => {
  233. // 获取投影坐标系
  234. const sourceProj = map.getView().getProjection();
  235. // ol/sphere里有getLength()和getArea()用来测量距离和区域面积,默认的投影坐标系是EPSG:3857, 其中有个options的参数,可以设置投影坐标系
  236. const length = sphere.getLength(line, {projection: sourceProj});
  237. // const length = getLength(line);
  238. let output;
  239. if (length > 100) {
  240. const km = Math.round((length / 1000) * 100) / 100;
  241. output = `${km} 千米 <br>${parseFloat(String(km * 0.53995)).toFixed(2)} 海里`;
  242. } else {
  243. output = `${Math.round(length * 100) / 100} m`;
  244. }
  245. return output;
  246. };
  247. //获取圆的面积
  248. const getCircleArea = (circle, projection) => {
  249. const P = 3.14
  250. const radius = getCircleRadius(circle, projection)
  251. return P * radius * radius
  252. }
  253. //获取圆的半径
  254. const getCircleRadius = (circle, projection) => {
  255. return circle.getRadius() * projection.getMetersPerUnit()
  256. }
  257. const formatArea = (polygon, type= 'polygon') => {
  258. let area
  259. const sourceProj = map.getView().getProjection();
  260. // 获取投影坐标系
  261. if (type === 'polygon') {
  262. area = sphere.getArea(polygon, {
  263. projection: sourceProj,
  264. });
  265. } else if (type === 'circle') {
  266. area = getCircleArea(polygon, sourceProj)
  267. }
  268. let output;
  269. if (area > 10000) {
  270. const km = Math.round((area / 1000000) * 100) / 100;
  271. output = `${km} 平方公里<br>${parseFloat(String(km * 0.38610)).toFixed(
  272. 2
  273. )} 平方英里`;
  274. } else {
  275. output = `${Math.round(area * 100) / 100} ` + " m<sup>2</sup>";
  276. }
  277. return output;
  278. };
  279. const addInteraction = () => {
  280. const id = 'baseDrawName'
  281. const draw = new interaction.Draw({
  282. source: _source,//测量绘制层数据源
  283. type: obj.rectangle ? 'LineString' : obj.featureType, //几何图形类型
  284. // @ts-ignore
  285. // geometryFunction: createBox(),
  286. geometryFunction: obj.rectangle ? createBox() : null,
  287. // geometryFunction: createRegularPolygon(6),
  288. style: commonStyle(obj.featureType === 'Point' ? true : false),
  289. });
  290. draw.set('showText', obj.featureType === 'Point' ? true : false)
  291. draw.set(drawFlag[0], drawFlag[1])
  292. draw.set(id, id)
  293. createMeasureTooltip(); //创建测量工具提示框
  294. createHelpTooltip(); //创建帮助提示框
  295. map.addInteraction(draw);
  296. let listener;
  297. //绑定交互绘制工具开始绘制的事件
  298. const drawstartHandle = (evt) => {
  299. sketch = evt.feature; //绘制的要素
  300. let tooltipCoord = evt.coordinate;// 绘制的坐标
  301. //绑定change事件,根据绘制几何类型得到测量长度值或面积值,并将其设置到测量工具提示框中显示
  302. listener = sketch.getGeometry().on('change', function (evt) {
  303. const geom = evt.target
  304. let output;
  305. if (geom.getType() === 'LineString') {
  306. output = formatLength(geom);//长度值
  307. tooltipCoord = geom.getLastCoordinate();//坐标
  308. } else if (geom.getType() === 'Polygon') {
  309. output = formatArea(geom);//面积值
  310. tooltipCoord = geom.getInteriorPoint().getCoordinates();//坐标
  311. } else if (geom.getType() === 'Circle') {
  312. output = formatArea(geom, 'circle');//面积值
  313. tooltipCoord = geom.getCenter()
  314. }
  315. toolDrawTooltipElement.innerHTML = output;//将测量值设置到测量工具提示框中显示
  316. measureTooltip.setPosition(tooltipCoord);//设置测量工具提示框的显示位置
  317. });
  318. }
  319. draw.on('drawstart', drawstartHandle);
  320. //绑定交互绘制工具结束绘制的事件
  321. const copy = (value) => {
  322. const str = document.createElement('input')
  323. str.setAttribute('value', value)
  324. document.body.appendChild(str)
  325. str.select()
  326. document.execCommand('copy')
  327. document.body.removeChild(str)
  328. }
  329. const drawendHandle = (evt) => {
  330. map.removeInteraction(map.getInteractions().getArray().filter(v => v.get(id) === id)[0]);
  331. // 标绘的时候不需要最终结果dom
  332. map.removeOverlay(map.getOverlayById('baseDrawHelpTooltipElementId'))
  333. toolDrawTooltipElement.parentNode.removeChild(toolDrawTooltipElement);
  334. sketch = null; //置空当前绘制的要素对象
  335. toolDrawTooltipElement = null; //置空测量工具提示框对象
  336. toolDrawHelpTooltipElement.parentNode.removeChild(toolDrawHelpTooltipElement);
  337. toolDrawHelpTooltipElement = null; //置空测量工具提示框对象
  338. unByKey(listener);
  339. draw.un('drawstart', drawstartHandle);
  340. draw.un('drawend', drawendHandle);
  341. map.removeInteraction(map.getInteractions().getArray().filter(v => v.get(id) === id)[0]);
  342. map.un('pointermove', pointerMoveHandler)
  343. const featEnd = evt.feature
  344. featEnd.set('isInit', true)
  345. featEnd.set(layerFlag[0], layerFlag[1])
  346. featEnd.setId(v4())
  347. }
  348. draw.on('drawend', drawendHandle);
  349. }
  350. addInteraction(); //调用加载绘制交互控件方法,添加绘图进行测量
  351. const pointerMoveHandler = (evt) => {
  352. if (evt.dragging) {
  353. return;
  354. }
  355. let helpMsg = '单击开始标绘';//当前默认提示信息
  356. //判断绘制几何类型设置相应的帮助提示信息
  357. if (sketch) {
  358. const geom = sketch.getGeometry()
  359. helpMsg = continueMsg;
  360. // if (geom.getType() === 'Polygon') {
  361. // helpMsg = continueMsg; //绘制多边形时提示相应内容
  362. // } else if (geom.getType() === 'LineString') {
  363. // helpMsg = continueMsg; //绘制线时提示相应内容
  364. // }
  365. }
  366. toolDrawHelpTooltipElement.innerHTML = helpMsg; //将提示信息设置到对话框中显示
  367. helpTooltip.setPosition(evt.coordinate);//设置帮助提示框的位置
  368. toolDrawHelpTooltipElement.classList.remove('hidden');//移除帮助提示框的隐藏样式进行显示
  369. };
  370. map.on('pointermove', pointerMoveHandler); //地图容器绑定鼠标移动事件,动态显示帮助提示框内容
  371. //地图绑定鼠标移出事件,鼠标移出时为帮助提示框设置隐藏样式
  372. try {
  373. map.getViewport().on('mouseout', () => {
  374. toolDrawHelpTooltipElement.addClass('hidden');
  375. });
  376. } catch (e) {
  377. }
  378. }
  379. }
  380. resolve(() => {
  381. const oldLayer = map.getLayers().getArray().filter(v => v.get(layerFlag[0]) === layerFlag[1])
  382. if (oldLayer) {
  383. oldLayer[0].setStyle(commonStyle(true))
  384. }
  385. // const oldDraw = map.getInteractions().getArray().filter(v => v.get(drawFlag[0]) === drawFlag[1])
  386. // if (oldDraw) {
  387. // oldDraw[0].setStyle(commonStyle(oldDraw[0].get('showText')))
  388. // }
  389. })
  390. }))
  391. }
  392. export const refreshModify = (map, _source) => {
  393. const oldModify = map.getInteractions().getArray().filter(v => v.get(modifyFlag[0]) === modifyFlag[1])
  394. if (oldModify) {
  395. map.removeInteraction(oldModify[0])
  396. }
  397. const modifyInteraction = new Modify({
  398. source: _source,
  399. });
  400. modifyInteraction.set(modifyFlag[0], modifyFlag[1])
  401. map.addInteraction(modifyInteraction)
  402. modifyInteraction.on('modifyend', evt => {
  403. try {
  404. const feat = evt.features.item(0)
  405. } catch {
  406. }
  407. })
  408. }