mapManage.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. import * as KMap from "@/utils/ol-map/KMap";
  2. import * as util from "@/common/ol_common.js";
  3. import config from "@/api/config.js";
  4. import Style from "ol/style/Style";
  5. import Icon from "ol/style/Icon";
  6. import Fill from "ol/style/Fill";
  7. import Stroke from "ol/style/Stroke";
  8. import Text from "ol/style/Text";
  9. import { Point, Polygon, MultiPolygon } from "ol/geom";
  10. import Feature from "ol/Feature";
  11. import DragPan from "ol/interaction/DragPan";
  12. import MouseWheelZoom from "ol/interaction/MouseWheelZoom";
  13. import PinchZoom from "ol/interaction/PinchZoom";
  14. import PinchRotate from "ol/interaction/PinchRotate";
  15. import DoubleClickZoom from "ol/interaction/DoubleClickZoom";
  16. import KeyboardPan from "ol/interaction/KeyboardPan";
  17. import KeyboardZoom from "ol/interaction/KeyboardZoom";
  18. import DragRotateAndZoom from "ol/interaction/DragRotateAndZoom";
  19. import Select from "ol/interaction/Select";
  20. import { singleClick } from "ol/events/condition";
  21. import { reactive } from "vue";
  22. import WKT from "ol/format/WKT.js";
  23. import GeoJSON from "ol/format/GeoJSON";
  24. import * as proj from "ol/proj";
  25. import { getArea } from "ol/sphere.js";
  26. import * as turf from "@turf/turf";
  27. const DEFAULT_ZONE_STYLE = {
  28. fill: "rgba(100, 0, 0, 0.45)",
  29. fillSelected: "rgba(100, 0, 0, 0.5)",
  30. stroke: "#E03131",
  31. };
  32. const VIEWPORT_INTERACTION_TYPES = [
  33. DragPan,
  34. MouseWheelZoom,
  35. PinchZoom,
  36. PinchRotate,
  37. DoubleClickZoom,
  38. KeyboardPan,
  39. KeyboardZoom,
  40. DragRotateAndZoom,
  41. ];
  42. function setViewportInteractionsActive(olMap, active) {
  43. olMap.getInteractions().forEach((ix) => {
  44. if (VIEWPORT_INTERACTION_TYPES.some((T) => ix instanceof T)) {
  45. ix.setActive(active);
  46. }
  47. });
  48. }
  49. export let mapLocation = reactive({
  50. data: null,
  51. });
  52. /**
  53. * @description 地图层对象
  54. */
  55. class MapManage {
  56. constructor() {
  57. let vectorStyle = new KMap.VectorStyle();
  58. this.vectorStyle = vectorStyle;
  59. this.regionDrawingActive = false;
  60. this.clickPointLayer = new KMap.VectorLayer("clickPointLayer", 9999, {
  61. style: () => {
  62. return new Style({
  63. image: new Icon({
  64. src: require("@/assets/img/home/garden-point.png"),
  65. scale: 0.5,
  66. anchor: [0.5, 0.5],
  67. }),
  68. });
  69. },
  70. });
  71. this.boundaryLayer = new KMap.VectorLayer("drawBoundaryLayer", 1050, {
  72. style: () => this.createBoundaryStyle(),
  73. });
  74. this.boundaryGeometry = null;
  75. this.constrainedDrawing = false;
  76. this.constrainedDrawingReady = false;
  77. this.zoneStyle = { ...DEFAULT_ZONE_STYLE };
  78. this.gridLayer = new KMap.VectorLayer("terrainGridLayer", 1100, {
  79. style: (feature) => {
  80. const selected = !!feature.get("selected");
  81. return new Style({
  82. fill: new Fill({
  83. color: selected ? this.zoneStyle.fillSelected : "rgba(255, 255, 255, 0.01)",
  84. }),
  85. stroke: new Stroke({
  86. color: selected ? this.zoneStyle.stroke : "#fff",
  87. width: selected ? 1.8 : 1.2,
  88. }),
  89. });
  90. },
  91. });
  92. this.existingVarietyLayer = new KMap.VectorLayer("existingVarietyLayer", 1080, {
  93. style: (feature) => this.createExistingVarietyStyle(feature),
  94. });
  95. this.gridToggleSelect = null;
  96. this.selectedGridIds = new Set();
  97. this.terrainGridItems = [];
  98. this.wktFormat = new WKT();
  99. this.editable = true;
  100. }
  101. createReadonlyPolygonStyle() {
  102. return new Style({
  103. fill: new Fill({
  104. color: "rgba(124, 124, 124, 0.5)",
  105. }),
  106. stroke: new Stroke({
  107. color: "rgba(255, 255, 255, 0.55)",
  108. width: 2,
  109. }),
  110. });
  111. }
  112. createExistingVarietyStyle(feature) {
  113. const name = String(feature.get("name") || "");
  114. const fill = feature.get("fill") || "rgba(76, 175, 80, 0.28)";
  115. const stroke = feature.get("stroke") || "#4CAF50";
  116. return [
  117. new Style({
  118. fill: new Fill({ color: fill }),
  119. stroke: new Stroke({
  120. color: stroke,
  121. width: 2,
  122. }),
  123. }),
  124. new Style({
  125. text: new Text({
  126. text: name,
  127. font: "13px sans-serif",
  128. fill: new Fill({ color: "#1F1F1F" }),
  129. backgroundFill: new Fill({ color: "#ffffff" }),
  130. padding: [4, 8, 4, 8],
  131. overflow: true,
  132. }),
  133. }),
  134. ];
  135. }
  136. createBoundaryStyle() {
  137. return new Style({
  138. fill: new Fill({
  139. color: "rgba(124, 124, 124, 0.12)",
  140. }),
  141. stroke: new Stroke({
  142. color: "rgba(255, 255, 255, 0.85)",
  143. width: 2,
  144. lineDash: [8, 4],
  145. }),
  146. });
  147. }
  148. createDrawnZoneStyle() {
  149. return new Style({
  150. fill: new Fill({
  151. color: this.zoneStyle.fill,
  152. }),
  153. stroke: new Stroke({
  154. color: this.zoneStyle.stroke,
  155. width: 1.8,
  156. }),
  157. });
  158. }
  159. initMap(location, target, options = {}) {
  160. const { editable = true, constrainedDrawing = false, onDrawOutsideBoundary, zoneStyle } = options;
  161. this.zoneStyle = zoneStyle ? { ...DEFAULT_ZONE_STYLE, ...zoneStyle } : { ...DEFAULT_ZONE_STYLE };
  162. this.editable = editable;
  163. this.constrainedDrawing = constrainedDrawing;
  164. this.onDrawOutsideBoundary = typeof onDrawOutsideBoundary === "function" ? onDrawOutsideBoundary : null;
  165. this.constrainedDrawingReady = false;
  166. this.boundaryGeometry = null;
  167. let level = 16;
  168. let coordinate = util.wktCastGeom(location).getFirstCoordinate();
  169. this.kmap = new KMap.Map(target, level, coordinate[0], coordinate[1], null, 8, 22);
  170. let xyz2 = config.base_img_url3 + "map/lby/{z}/{x}/{y}.png";
  171. this.kmap.addXYZLayer(xyz2, { minZoom: 8, maxZoom: 22 }, 2);
  172. // this.kmap.addLayer(this.clickPointLayer.layer);
  173. this.kmap.addLayer(this.boundaryLayer.layer);
  174. this.kmap.addLayer(this.existingVarietyLayer.layer);
  175. this.kmap.addLayer(this.gridLayer.layer);
  176. if (this.editable) {
  177. this.kmap.initDraw(() => {});
  178. this.kmap.modifyDraw();
  179. this.setRegionDrawingActive(false);
  180. } else if (this.constrainedDrawing) {
  181. this.setupConstrainedDrawing();
  182. this.setConstrainedDrawingActive(false);
  183. }
  184. }
  185. isCoordinateInsideBoundary(coordinate) {
  186. if (!this.boundaryGeometry || !coordinate || !this.kmap) return false;
  187. try {
  188. return this.boundaryGeometry.intersectsCoordinate(coordinate);
  189. } catch {
  190. return false;
  191. }
  192. }
  193. notifyDrawOutsideBoundary() {
  194. this.onDrawOutsideBoundary?.();
  195. }
  196. getLastCoordinateFromGeometry(geometry) {
  197. if (!geometry || typeof geometry.getType !== "function") return null;
  198. const type = geometry.getType();
  199. if (type === "Point") return geometry.getCoordinates();
  200. if (type === "LineString") {
  201. const coords = geometry.getCoordinates();
  202. return coords.length ? coords[coords.length - 1] : null;
  203. }
  204. if (type === "Polygon") {
  205. const ring = geometry.getCoordinates()[0];
  206. return ring?.length ? ring[ring.length - 1] : null;
  207. }
  208. if (type === "MultiPolygon") {
  209. const polys = geometry.getCoordinates();
  210. const ring = polys[polys.length - 1]?.[0];
  211. return ring?.length ? ring[ring.length - 1] : null;
  212. }
  213. return null;
  214. }
  215. /** 区域外勾画:中止当前绘制并移除无效地块 */
  216. rejectOutsideDraw(feature) {
  217. if (feature && this.kmap?.polygonLayer?.source) {
  218. this.kmap.polygonLayer.source.removeFeature(feature);
  219. }
  220. if (this.kmap?.draw && typeof this.kmap.draw.abortDrawing === "function") {
  221. this.kmap.draw.abortDrawing();
  222. }
  223. this.notifyDrawOutsideBoundary();
  224. }
  225. unbindSketchBoundaryConstraint(sketch, listener) {
  226. sketch?.getGeometry()?.un("change", listener);
  227. }
  228. bindSketchBoundaryConstraint(sketch) {
  229. const onSketchChange = () => {
  230. const geometry = sketch.getGeometry();
  231. if (!geometry) return;
  232. const type = geometry.getType();
  233. // 仅在手绘轨迹(线)阶段判断越界;面要素未完成时 intersect 会误判
  234. if (type !== "LineString" && type !== "Point") return;
  235. const last = this.getLastCoordinateFromGeometry(geometry);
  236. if (last && !this.isCoordinateInsideBoundary(last)) {
  237. this.unbindSketchBoundaryConstraint(sketch, onSketchChange);
  238. this.rejectOutsideDraw();
  239. }
  240. };
  241. sketch.getGeometry()?.on("change", onSketchChange);
  242. const cleanup = () => this.unbindSketchBoundaryConstraint(sketch, onSketchChange);
  243. this.kmap.draw.once("drawend", cleanup);
  244. this.kmap.draw.once("drawabort", cleanup);
  245. }
  246. setupConstrainedDrawing() {
  247. if (!this.kmap || this.constrainedDrawingReady) return;
  248. this.constrainedDrawingReady = true;
  249. this.kmap.initDraw((e) => {
  250. if (!e.feature) return;
  251. if (!this.clipFeatureToBoundary(e.feature)) {
  252. if (this.kmap?.polygonLayer?.source) {
  253. this.kmap.polygonLayer.source.removeFeature(e.feature);
  254. }
  255. this.notifyDrawOutsideBoundary();
  256. }
  257. });
  258. this.kmap.draw.on("drawstart", (e) => {
  259. const coordinate = e.coordinate || this.getLastCoordinateFromGeometry(e.feature?.getGeometry());
  260. if (!coordinate || !this.isCoordinateInsideBoundary(coordinate)) {
  261. this.rejectOutsideDraw();
  262. return;
  263. }
  264. this.bindSketchBoundaryConstraint(e.feature);
  265. });
  266. this.kmap.modifyDraw((e) => {
  267. e.features.forEach((feature) => {
  268. if (!this.clipFeatureToBoundary(feature)) {
  269. if (this.kmap?.polygonLayer?.source) {
  270. this.kmap.polygonLayer.source.removeFeature(feature);
  271. }
  272. this.notifyDrawOutsideBoundary();
  273. }
  274. });
  275. });
  276. }
  277. setConstrainedDrawingActive(active) {
  278. if (!this.kmap) return;
  279. if (this.kmap.draw) {
  280. this.kmap.draw.setActive(active);
  281. }
  282. if (this.kmap.modify) {
  283. this.kmap.modify.setActive(active);
  284. }
  285. }
  286. enableConstrainedDrawing() {
  287. if (!this.boundaryGeometry) return;
  288. this.setupConstrainedDrawing();
  289. this.setConstrainedDrawingActive(true);
  290. }
  291. intersectWithBoundary(geometry) {
  292. if (!this.boundaryGeometry || !geometry || !this.kmap) return null;
  293. const geoJson = new GeoJSON();
  294. const projection = this.kmap.map.getView().getProjection();
  295. const opts = {
  296. dataProjection: "EPSG:4326",
  297. featureProjection: projection,
  298. };
  299. try {
  300. const drawGeo = geoJson.writeGeometryObject(geometry, opts);
  301. const boundaryGeo = geoJson.writeGeometryObject(this.boundaryGeometry, opts);
  302. const drawnFeature = turf.feature(drawGeo);
  303. const boundaryFeature = turf.feature(boundaryGeo);
  304. let result = null;
  305. try {
  306. result = turf.intersect(turf.featureCollection([drawnFeature, boundaryFeature]));
  307. } catch {
  308. result = turf.intersect(drawnFeature, boundaryFeature);
  309. }
  310. if (!result?.geometry) return null;
  311. return geoJson.readGeometry(result.geometry, opts);
  312. } catch {
  313. return null;
  314. }
  315. }
  316. clipFeatureToBoundary(feature) {
  317. if (!feature || !this.boundaryGeometry || !this.kmap?.polygonLayer?.source) return false;
  318. const geometry = feature.getGeometry();
  319. if (!geometry) return false;
  320. const clipped = this.intersectWithBoundary(geometry);
  321. if (!clipped) {
  322. this.kmap.polygonLayer.source.removeFeature(feature);
  323. return false;
  324. }
  325. feature.setGeometry(clipped);
  326. feature.setStyle(this.createDrawnZoneStyle());
  327. return true;
  328. }
  329. setBoundaryWkt(wkt) {
  330. if (!this.kmap || !this.boundaryLayer?.source || !wkt) return;
  331. this.boundaryLayer.source.clear();
  332. const mapProjection = this.kmap.map.getView().getProjection();
  333. const geometry = this.wktFormat.readGeometry(String(wkt).trim(), {
  334. dataProjection: "EPSG:4326",
  335. featureProjection: mapProjection,
  336. });
  337. this.boundaryGeometry = geometry.clone();
  338. const feature = new Feature({ geometry });
  339. feature.set("isBoundary", true);
  340. this.boundaryLayer.addFeature(feature);
  341. this.fitBoundaryView();
  342. }
  343. clearBoundaryLayer() {
  344. this.boundaryLayer?.source?.clear();
  345. this.boundaryGeometry = null;
  346. }
  347. fitBoundaryView() {
  348. if (!this.kmap || !this.boundaryLayer?.source) return;
  349. const extent = this.boundaryLayer.source.getExtent();
  350. if (!extent || extent.some((v) => !Number.isFinite(v))) return;
  351. this.kmap.getView().fit(extent, { duration: 500, padding: [40, 40, 40, 40] });
  352. }
  353. setDrawnAreaGeometry(geometryArr) {
  354. if (!this.kmap?.polygonLayer?.source || !Array.isArray(geometryArr)) return;
  355. this.kmap.polygonLayer.source.clear();
  356. const mapProjection = this.kmap.map.getView().getProjection();
  357. geometryArr.forEach((item) => {
  358. try {
  359. const geometry = this.wktFormat.readGeometry(String(item).trim(), {
  360. dataProjection: "EPSG:4326",
  361. featureProjection: mapProjection,
  362. });
  363. const feature = new Feature({ geometry });
  364. this.clipFeatureToBoundary(feature);
  365. if (feature.getGeometry()) {
  366. this.kmap.polygonLayer.source.addFeature(feature);
  367. }
  368. } catch {
  369. /* 单条解析失败则跳过 */
  370. }
  371. });
  372. }
  373. /**
  374. * 是否允许平移/缩放、勾画与编辑;为 false 时同时隐藏中心点位图标
  375. */
  376. setRegionDrawingActive(active) {
  377. if (!this.kmap) return;
  378. this.regionDrawingActive = active;
  379. setViewportInteractionsActive(this.kmap.map, active);
  380. if (this.kmap.draw) {
  381. this.kmap.draw.setActive(active);
  382. }
  383. if (this.kmap.modify) {
  384. this.kmap.modify.setActive(active);
  385. }
  386. if (active) {
  387. const c = this.kmap.getView().getCenter();
  388. this.setMapPoint(c);
  389. } else {
  390. // this.clickPointLayer.source.clear();
  391. }
  392. }
  393. enableRegionDrawing() {
  394. this.setRegionDrawingActive(true);
  395. }
  396. enableMapInteraction() {
  397. if (!this.kmap) return;
  398. setViewportInteractionsActive(this.kmap.map, true);
  399. }
  400. /**
  401. * 根据中心点和亩数生成正方形 WKT
  402. * @param {number[]} center [lng, lat]
  403. * @param {number} mu 面积(亩)
  404. */
  405. generateSquareWktByMu(center, mu = 60) {
  406. const lng = parseFloat(center[0]);
  407. const lat = parseFloat(center[1]);
  408. const halfSide = Math.sqrt(mu * 666.67) / 2;
  409. const latDelta = halfSide / 111000;
  410. const lngDelta = halfSide / (111000 * Math.cos((lat * Math.PI) / 180));
  411. const ring = [
  412. [lng - lngDelta, lat + latDelta],
  413. [lng + lngDelta, lat + latDelta],
  414. [lng + lngDelta, lat - latDelta],
  415. [lng - lngDelta, lat - latDelta],
  416. [lng - lngDelta, lat + latDelta],
  417. ];
  418. const coordinates = ring.map((point) => `${point[0]} ${point[1]}`).join(", ");
  419. return `MULTIPOLYGON (((${coordinates})))`;
  420. }
  421. /**
  422. * 以当前地图中心生成指定亩数的正方形区域
  423. * @param {number} mu 面积(亩)
  424. * @returns {string|null} WKT
  425. */
  426. setDefaultSquareAtCenter(mu = 60) {
  427. if (!this.kmap) return null;
  428. const center = this.kmap.getView().getCenter();
  429. const wkt = this.generateSquareWktByMu(center, mu);
  430. this.setBoundaryWkt(wkt);
  431. this.setMapPoint(center);
  432. this.enableConstrainedDrawing();
  433. return wkt;
  434. }
  435. setCenterAndSquare(center, mu = 60) {
  436. if (!this.kmap) return null;
  437. this.kmap.getView().animate({
  438. center,
  439. zoom: 16,
  440. duration: 0,
  441. });
  442. this.setMapPoint(center);
  443. const wkt = this.generateSquareWktByMu(center, mu);
  444. this.setBoundaryWkt(wkt);
  445. this.enableConstrainedDrawing();
  446. return wkt;
  447. }
  448. setMapPoint(coordinate) {
  449. // this.clickPointLayer.source.clear();
  450. let point = new Feature(new Point(coordinate));
  451. // this.clickPointLayer.addFeature(point);
  452. }
  453. showCenterMarker(coordinate, iconSrc) {
  454. if (!this.kmap || !coordinate) return;
  455. if (!this.centerMarkerLayer) {
  456. const src = iconSrc || require("@/assets/img/home/garden-point.png");
  457. this.centerMarkerLayer = new KMap.VectorLayer("centerMarkerLayer", 9998, {
  458. style: () =>
  459. new Style({
  460. image: new Icon({
  461. src,
  462. scale: 0.45,
  463. anchor: [0.5, 1],
  464. }),
  465. }),
  466. });
  467. this.kmap.addLayer(this.centerMarkerLayer.layer);
  468. }
  469. this.centerMarkerLayer.source.clear();
  470. this.centerMarkerLayer.addFeature(new Feature(new Point(coordinate)));
  471. }
  472. setMapPosition(center) {
  473. this.kmap.getView().animate({
  474. center,
  475. zoom: 16,
  476. duration: 0,
  477. });
  478. if (this.regionDrawingActive) {
  479. this.setMapPoint(center);
  480. }
  481. }
  482. clearLayer() {
  483. if (!this.kmap?.polygonLayer?.source) return;
  484. if (this.kmap.draw && typeof this.kmap.draw.abortDrawing === "function") {
  485. this.kmap.draw.abortDrawing();
  486. }
  487. this.kmap.polygonLayer.source.clear();
  488. this.clearGridLayer();
  489. }
  490. clearAllLayers() {
  491. this.clearLayer();
  492. this.clearBoundaryLayer();
  493. this.clearExistingVarietyZones();
  494. }
  495. clearExistingVarietyZones() {
  496. this.existingVarietyLayer?.source?.clear();
  497. }
  498. /**
  499. * 展示已有品种种植范围(只读),不参与勾画结果
  500. * @param {{ id?: string|number, name: string, polygon: string, fill?: string, stroke?: string }[]} zones
  501. */
  502. setExistingVarietyZones(zones = []) {
  503. if (!this.kmap || !this.existingVarietyLayer?.source) return;
  504. this.clearExistingVarietyZones();
  505. const projection = this.kmap.map.getView().getProjection();
  506. const list = Array.isArray(zones) ? zones : [];
  507. list.forEach((item) => {
  508. const wkt = item?.polygon || item?.wkt;
  509. if (!wkt) return;
  510. try {
  511. const geometry = this.wktFormat.readGeometry(String(wkt).trim(), {
  512. dataProjection: "EPSG:4326",
  513. featureProjection: projection,
  514. });
  515. const feature = new Feature({ geometry });
  516. feature.set("id", item.id);
  517. feature.set("name", item.name || "");
  518. feature.set("fill", item.fill);
  519. feature.set("stroke", item.stroke);
  520. feature.set("readonly", true);
  521. this.existingVarietyLayer.source.addFeature(feature);
  522. } catch (e) {
  523. console.warn("[MapManage] existing variety polygon parse failed", e);
  524. }
  525. });
  526. this.existingVarietyLayer.layer.changed();
  527. }
  528. clearGridLayer() {
  529. this.unbindGridClick();
  530. this.gridLayer?.source?.clear();
  531. this.selectedGridIds?.clear();
  532. this.terrainGridItems = [];
  533. }
  534. unbindGridClick() {
  535. if (this.gridToggleSelect && this.kmap?.map) {
  536. this.kmap.map.removeInteraction(this.gridToggleSelect);
  537. }
  538. this.gridToggleSelect = null;
  539. }
  540. bindGridClick() {
  541. if (!this.kmap?.map || !this.gridLayer?.layer) return;
  542. this.unbindGridClick();
  543. const selectedStyle = new Style({
  544. fill: new Fill({
  545. color: this.zoneStyle.fillSelected,
  546. }),
  547. stroke: new Stroke({
  548. color: this.zoneStyle.stroke,
  549. width: 1.8,
  550. }),
  551. });
  552. this.gridToggleSelect = new Select({
  553. condition: singleClick,
  554. toggleCondition: singleClick,
  555. layers: [this.gridLayer.layer],
  556. multi: true,
  557. hitTolerance: 8,
  558. style: selectedStyle,
  559. });
  560. this.gridToggleSelect.on("select", (e) => {
  561. e.selected.forEach((feature) => {
  562. feature.set("selected", true);
  563. this.selectedGridIds.add(feature.get("gridId"));
  564. feature.changed();
  565. });
  566. e.deselected.forEach((feature) => {
  567. feature.set("selected", false);
  568. this.selectedGridIds.delete(feature.get("gridId"));
  569. feature.changed();
  570. });
  571. this.gridLayer.layer.changed();
  572. });
  573. this.kmap.map.addInteraction(this.gridToggleSelect);
  574. }
  575. getSelectedGrids() {
  576. const empty = {
  577. gridIds: [],
  578. geometryArr: [],
  579. parcels: [],
  580. mianji: "0.00",
  581. mergedGeometry: "",
  582. };
  583. if (!this.kmap || !this.gridLayer?.source) return empty;
  584. const projection = this.kmap.map.getView().getProjection();
  585. const gridIds = [];
  586. const geometryArr = [];
  587. const parcels = [];
  588. let totalMu = 0;
  589. this.gridLayer.source.getFeatures().forEach((feature) => {
  590. if (!feature.get("selected")) return;
  591. const geometry = feature.getGeometry();
  592. if (!geometry) return;
  593. const gridId = feature.get("gridId");
  594. gridIds.push(gridId);
  595. const wkt = this.wktFormat.writeGeometry(geometry, {
  596. dataProjection: "EPSG:4326",
  597. featureProjection: projection,
  598. });
  599. geometryArr.push(wkt);
  600. let geom = geometry.clone();
  601. geom.transform(proj.get("EPSG:4326"), proj.get("EPSG:38572"));
  602. let mu = getArea(geom);
  603. mu = (mu + mu / 2) / 1000;
  604. totalMu += mu;
  605. parcels.push({ gridId, wkt, mianji: Number(mu.toFixed(2)) });
  606. });
  607. return {
  608. gridIds,
  609. geometryArr,
  610. parcels,
  611. mianji: totalMu.toFixed(2),
  612. mergedGeometry: this.mergeGeometryWkts(geometryArr),
  613. };
  614. }
  615. polygonCoordSetsFromGeometry(geometry) {
  616. if (!geometry || typeof geometry.getType !== "function") return [];
  617. const type = geometry.getType();
  618. if (type === "Polygon") return [geometry.getCoordinates()];
  619. if (type === "MultiPolygon") return geometry.getCoordinates();
  620. return [];
  621. }
  622. /**
  623. * 将多个 WKT 面合并为一个(单块返回 POLYGON,多块返回 MULTIPOLYGON)
  624. * @param {string[]} wktArr
  625. * @returns {string}
  626. */
  627. mergeGeometryWkts(wktArr) {
  628. if (!Array.isArray(wktArr) || wktArr.length === 0) return "";
  629. const trimmed = wktArr
  630. .map((item) => String(item).trim())
  631. .filter((item) => item.length > 10);
  632. if (trimmed.length === 0) return "";
  633. if (trimmed.length === 1) return trimmed[0];
  634. const wktOpts = {
  635. dataProjection: "EPSG:4326",
  636. featureProjection: "EPSG:4326",
  637. };
  638. const coordSets = [];
  639. trimmed.forEach((wkt) => {
  640. try {
  641. const geometry = this.wktFormat.readGeometry(wkt, wktOpts);
  642. coordSets.push(...this.polygonCoordSetsFromGeometry(geometry));
  643. } catch {
  644. /* 单条解析失败则跳过 */
  645. }
  646. });
  647. if (coordSets.length === 0) return trimmed[0];
  648. if (coordSets.length === 1) {
  649. return this.wktFormat.writeGeometry(new Polygon(coordSets[0]), wktOpts);
  650. }
  651. return this.wktFormat.writeGeometry(new MultiPolygon(coordSets), wktOpts);
  652. }
  653. getSelectedGridIds() {
  654. return this.getSelectedGrids().gridIds;
  655. }
  656. /**
  657. * 接口网格 geometry 转 Polygon(支持 MULTIPOINT / POLYGON)
  658. */
  659. gridGeometryToPolygon(geometryWkt) {
  660. if (!this.kmap || !geometryWkt) return null;
  661. const projection = this.kmap.map.getView().getProjection();
  662. let geom;
  663. try {
  664. geom = this.wktFormat.readGeometry(String(geometryWkt).trim(), {
  665. dataProjection: "EPSG:4326",
  666. featureProjection: projection,
  667. });
  668. } catch {
  669. return null;
  670. }
  671. const type = geom.getType();
  672. if (type === "Polygon") return geom;
  673. if (type === "MultiPolygon") {
  674. const polygons = geom.getPolygons();
  675. return polygons.length ? polygons[0] : null;
  676. }
  677. if (type !== "MultiPoint") return null;
  678. const coords = geom.getCoordinates();
  679. if (!coords || coords.length < 3) return null;
  680. const ring = coords.map((c) => [...c]);
  681. const first = ring[0];
  682. const last = ring[ring.length - 1];
  683. if (first[0] !== last[0] || first[1] !== last[1]) {
  684. ring.push([...first]);
  685. }
  686. return new Polygon([ring]);
  687. }
  688. /**
  689. * 渲染地形网格(generateGrid 接口返回)
  690. * @param {{ id: number, geometry: string, area_m2?: number }[]} gridItems
  691. */
  692. setTerrainGrids(gridItems) {
  693. if (!this.kmap || !this.gridLayer?.source) return;
  694. this.clearGridLayer();
  695. if (!Array.isArray(gridItems) || !gridItems.length) return;
  696. this.terrainGridItems = gridItems.map((item) => ({
  697. id: item.id,
  698. geometry: item.geometry,
  699. area_m2: item.area_m2,
  700. }));
  701. gridItems.forEach((item) => {
  702. const polygon = this.gridGeometryToPolygon(item?.geometry);
  703. if (!polygon) return;
  704. const feature = new Feature({ geometry: polygon });
  705. feature.set("gridId", item.id);
  706. feature.set("area_m2", item.area_m2);
  707. feature.set("selected", false);
  708. this.gridLayer.addFeature(feature);
  709. });
  710. this.bindGridClick();
  711. }
  712. fitGridView() {
  713. if (!this.kmap || !this.gridLayer?.source) return;
  714. const extent = this.gridLayer.source.getExtent();
  715. if (!extent || extent.some((v) => !Number.isFinite(v))) return;
  716. this.kmap.getView().fit(extent, { duration: 500, padding: [40, 40, 40, 40] });
  717. }
  718. getBoundaryWkt() {
  719. if (!this.boundaryGeometry || !this.kmap) return "";
  720. return this.wktFormat.writeGeometry(this.boundaryGeometry, {
  721. dataProjection: "EPSG:4326",
  722. featureProjection: this.kmap.map.getView().getProjection(),
  723. });
  724. }
  725. getDisplayAreaWkt() {
  726. if (!this.kmap?.polygonLayer?.source) return "";
  727. const projection = this.kmap.map.getView().getProjection();
  728. const geometryArr = [];
  729. this.kmap.polygonLayer.source.getFeatures().forEach((feature) => {
  730. const geometry = feature.getGeometry();
  731. if (!geometry) return;
  732. geometryArr.push(
  733. this.wktFormat.writeGeometry(geometry, {
  734. dataProjection: "EPSG:4326",
  735. featureProjection: projection,
  736. })
  737. );
  738. });
  739. return this.mergeGeometryWkts(geometryArr);
  740. }
  741. getTerrainGridItems() {
  742. if (this.terrainGridItems.length) {
  743. return this.terrainGridItems.map((item) => ({ ...item }));
  744. }
  745. if (!this.kmap || !this.gridLayer?.source) return [];
  746. const projection = this.kmap.map.getView().getProjection();
  747. return this.gridLayer.source.getFeatures().map((feature) => {
  748. const geometry = feature.getGeometry();
  749. return {
  750. id: feature.get("gridId"),
  751. geometry: geometry
  752. ? this.wktFormat.writeGeometry(geometry, {
  753. dataProjection: "EPSG:4326",
  754. featureProjection: projection,
  755. })
  756. : "",
  757. area_m2: feature.get("area_m2"),
  758. };
  759. });
  760. }
  761. restoreSelectedGrids(gridIds) {
  762. if (!this.gridLayer?.source || !Array.isArray(gridIds)) return;
  763. const idSet = new Set(gridIds.map((id) => String(id)));
  764. this.selectedGridIds.clear();
  765. this.gridLayer.source.getFeatures().forEach((feature) => {
  766. const gridId = feature.get("gridId");
  767. const selected = idSet.has(String(gridId));
  768. feature.set("selected", selected);
  769. if (selected) {
  770. this.selectedGridIds.add(gridId);
  771. }
  772. feature.changed();
  773. });
  774. this.gridLayer.layer.changed();
  775. }
  776. destroyMap() {
  777. this.unbindGridClick();
  778. this.clearAllLayers();
  779. this.centerMarkerLayer = null;
  780. if (this.kmap && typeof this.kmap.destroy === "function") {
  781. this.kmap.destroy();
  782. }
  783. this.kmap = null;
  784. this.regionDrawingActive = false;
  785. this.constrainedDrawing = false;
  786. this.constrainedDrawingReady = false;
  787. this.boundaryGeometry = null;
  788. this.onDrawOutsideBoundary = null;
  789. this.selectedGridIds?.clear();
  790. }
  791. /**
  792. * 地图上全部已勾画地块:WKT 列表、每块亩数、合计亩数(亩换算与互动勾画页一致)
  793. */
  794. getAreaGeometry() {
  795. if (!this.kmap) {
  796. return { geometryArr: [], mianji: "0.00", parcels: [] };
  797. }
  798. const features = this.kmap.getLayerFeatures();
  799. const format = new WKT();
  800. const projection = this.kmap.map.getView().getProjection();
  801. const geometryArr = [];
  802. const parcels = [];
  803. let totalMu = 0;
  804. features.forEach((item) => {
  805. const geometry = item.getGeometry();
  806. if (!geometry) return;
  807. const wkt = format.writeGeometry(geometry, {
  808. dataProjection: "EPSG:4326",
  809. featureProjection: projection,
  810. });
  811. geometryArr.push(wkt);
  812. let geom = geometry.clone();
  813. geom.transform(proj.get("EPSG:4326"), proj.get("EPSG:38572"));
  814. let mu = getArea(geom);
  815. mu = (mu + mu / 2) / 1000;
  816. totalMu += mu;
  817. parcels.push({ wkt, mianji: Number(mu.toFixed(2)) });
  818. });
  819. return {
  820. geometryArr,
  821. mianji: totalMu.toFixed(2),
  822. parcels,
  823. };
  824. }
  825. setAreaGeometry(geometryArr) {
  826. this.clearLayer();
  827. if (!this.kmap) return;
  828. const format = new WKT();
  829. const mapProjection = this.kmap.map.getView().getProjection();
  830. geometryArr.forEach((item) => {
  831. const geometry = format.readGeometry(item, {
  832. dataProjection: "EPSG:4326",
  833. featureProjection: mapProjection,
  834. });
  835. const feature = new Feature({ geometry });
  836. if (!this.editable) {
  837. feature.setStyle(this.createReadonlyPolygonStyle());
  838. }
  839. this.kmap.polygonLayer.source.addFeature(feature);
  840. });
  841. if (this.boundaryGeometry) {
  842. this.fitBoundaryView();
  843. } else {
  844. this.fitView();
  845. }
  846. }
  847. fitView(){
  848. let extent = this.kmap.polygonLayer.source.getExtent()
  849. // 地图自适应到区域可视范围
  850. this.kmap.getView().fit(extent, { duration: 500, padding: [40, 40, 40, 40] });
  851. }
  852. }
  853. export default MapManage;