editMap copy.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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 { Point } from 'ol/geom';
  9. import Feature from "ol/Feature";
  10. import * as proj from "ol/proj";
  11. import { getArea } from 'ol/sphere.js';
  12. import WKT from "ol/format/WKT.js";
  13. import GeoJSON from "ol/format/GeoJSON.js";
  14. import * as turf from "@turf/turf";
  15. import proj4 from "proj4"
  16. import { register } from "ol/proj/proj4";
  17. proj4.defs("EPSG:38572","+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs +type=crs");
  18. register(proj4);
  19. /**
  20. * @description 地图层对象
  21. */
  22. class EditMap {
  23. constructor() {
  24. let that = this;
  25. let vectorStyle = new KMap.VectorStyle();
  26. this.vectorStyle = vectorStyle;
  27. // 位置图标
  28. this.clickPointLayer = new KMap.VectorLayer("clickPointLayer", 9999, {
  29. style: (f) => {
  30. return new Style({
  31. image: new Icon({
  32. src: require("@/assets/img/home/garden-point.png"),
  33. scale: 0.5,
  34. anchor: [0.5, 1],
  35. }),
  36. });
  37. },
  38. });
  39. // 小网格图层(约 1 亩参考网格)
  40. this.gridLayer = new KMap.VectorLayer("gridLayer", 900, {
  41. style: (feature) => {
  42. const selected = !!feature.get("selected");
  43. return new Style({
  44. fill: new Fill({
  45. color: selected ? "rgba(255, 64, 64, 0.45)" : "rgba(255, 255, 255, 0.08)",
  46. }),
  47. stroke: new Stroke({
  48. color: selected ? "rgba(255, 64, 64, 0.95)" : "rgba(255, 255, 255, 0.4)",
  49. width: selected ? 1.8 : 1,
  50. }),
  51. });
  52. },
  53. });
  54. this.selectedGridIds = new Set();
  55. this.gridClickHandlerBound = false;
  56. // 1 亩约 666.67m²,正方形边长约 25.82m
  57. this.gridSideKm = 0.02582;
  58. }
  59. initMap(location, target) {
  60. let level = 16;
  61. let coordinate = util.wktCastGeom(location).getFirstCoordinate();
  62. this.kmap = new KMap.Map(target, level, coordinate[0], coordinate[1], null, 8, 22);
  63. let xyz2 = config.base_img_url3 + "map/lby/{z}/{x}/{y}.png";
  64. this.kmap.addXYZLayer(xyz2, { minZoom: 8, maxZoom: 22 }, 2);
  65. this.kmap.addLayer(this.clickPointLayer.layer);
  66. this.kmap.addLayer(this.gridLayer.layer);
  67. this.setMapPoint(coordinate)
  68. this.kmap.initDraw((e) => {
  69. this.rebuildGridFromPolygon();
  70. })
  71. // 监听drawstart事件,在开始绘制前检查是否已有地块
  72. this.kmap.draw.on('drawstart', (e) => {
  73. const features = this.kmap.getLayerFeatures();
  74. if (features && features.length >= 1) {
  75. // 提示用户先删除当前地块
  76. this.onDrawLimit && this.onDrawLimit();
  77. // 取消本次绘制
  78. this.kmap.draw.abortDrawing();
  79. }
  80. });
  81. this.kmap.startDraw()
  82. this.kmap.modifyDraw(() => {
  83. this.rebuildGridFromPolygon();
  84. })
  85. this.bindGridClick();
  86. }
  87. setAreaGeometry(geometryArr, needFitView = false) {
  88. let that = this
  89. geometryArr.map(item => {
  90. // 不使用 setLayerWkt,而是手动添加要素,避免自动缩放视图
  91. const format = new WKT()
  92. const mapProjection = that.kmap.map.getView().getProjection()
  93. let geometry = format.readGeometry(item, {
  94. dataProjection: 'EPSG:4326',
  95. featureProjection: mapProjection
  96. })
  97. let f = new Feature({ geometry: geometry })
  98. that.kmap.polygonLayer.source.addFeature(f)
  99. })
  100. this.rebuildGridFromPolygon();
  101. // 根据参数决定是否需要自适应地块范围
  102. if (needFitView) {
  103. this.fitView()
  104. }
  105. }
  106. fitView(){
  107. let extent = this.kmap.polygonLayer.source.getExtent()
  108. // 地图自适应到区域可视范围
  109. this.kmap.getView().fit(extent, { duration: 500, padding: [100, 100, 100, 100] });
  110. }
  111. clearLayer(){
  112. // this.kmap.removeLayer(this.clickPointLayer.layer)
  113. this.kmap.polygonLayer.source.clear();
  114. this.gridLayer.source.clear();
  115. this.selectedGridIds.clear();
  116. }
  117. getAreaGeometry() {
  118. const features = this.kmap.getLayerFeatures()
  119. let geometryArr = []
  120. let area = 0
  121. const format = new WKT()
  122. // 获取图层上的Polygon,转成WKT用于回显
  123. features.forEach(item => {
  124. // 使用 writeGeometry 而不是 writeFeature,因为 setLayerWkt 期望的是几何体的 WKT
  125. const geometry = item.getGeometry()
  126. geometryArr.push(format.writeGeometry(geometry, {
  127. dataProjection: 'EPSG:4326',
  128. featureProjection: this.kmap.map.getView().getProjection()
  129. }))
  130. let geom = geometry.clone()
  131. geom.transform(proj.get("EPSG:4326"), proj.get("EPSG:38572"))
  132. let areaItem = getArea(geom)
  133. areaItem = (areaItem + areaItem / 2) / 1000;
  134. area += areaItem
  135. })
  136. return {geometryArr, mianji: area.toFixed(2)} // 修改为 mianji 字段,与创建页面保持一致
  137. }
  138. setMapPosition(center) {
  139. this.kmap.getView().animate({
  140. center,
  141. zoom: 17,
  142. duration: 500,
  143. });
  144. this.setMapPoint(center)
  145. }
  146. setMapPoint(coordinate) {
  147. this.clickPointLayer.source.clear()
  148. let point = new Feature(new Point(coordinate))
  149. this.clickPointLayer.addFeature(point)
  150. }
  151. // 删除当前地块
  152. deleteCurrentPolygon() {
  153. this.kmap.polygonLayer.source.clear();
  154. this.gridLayer.source.clear();
  155. this.selectedGridIds.clear();
  156. }
  157. // 设置绘制限制回调
  158. setDrawLimitCallback(callback) {
  159. this.onDrawLimit = callback;
  160. }
  161. bindGridClick() {
  162. if (!this.kmap?.map || this.gridClickHandlerBound) return;
  163. this.gridClickHandlerBound = true;
  164. this.kmap.on("singleclick", (evt) => {
  165. let hitFeature = null;
  166. this.kmap.map.forEachFeatureAtPixel(evt.pixel, (feature, layer) => {
  167. if (layer === this.gridLayer.layer) {
  168. hitFeature = feature;
  169. return feature;
  170. }
  171. return null;
  172. });
  173. if (!hitFeature) return;
  174. const gridId = hitFeature.get("gridId");
  175. const isSelected = !!hitFeature.get("selected");
  176. hitFeature.set("selected", !isSelected);
  177. if (isSelected) {
  178. this.selectedGridIds.delete(gridId);
  179. } else {
  180. this.selectedGridIds.add(gridId);
  181. }
  182. hitFeature.changed();
  183. });
  184. }
  185. rebuildGridFromPolygon() {
  186. if (!this.kmap?.polygonLayer?.source || !this.gridLayer?.source) return;
  187. const features = this.kmap.polygonLayer.source.getFeatures();
  188. this.gridLayer.source.clear();
  189. this.selectedGridIds.clear();
  190. if (!features || !features.length) return;
  191. const format = new WKT();
  192. const geojsonFormat = new GeoJSON();
  193. const polygonGeometries = [];
  194. features.forEach((feature) => {
  195. const geometry = feature.getGeometry();
  196. if (!geometry) return;
  197. const wkt = format.writeGeometry(geometry, {
  198. dataProjection: "EPSG:4326",
  199. featureProjection: this.kmap.map.getView().getProjection(),
  200. });
  201. const turfGeom = turf.wktToGeoJSON ? turf.wktToGeoJSON(wkt) : null;
  202. if (turfGeom) {
  203. polygonGeometries.push(turfGeom);
  204. return;
  205. }
  206. // 回退:用 OL 读为 GeoJSON geometry
  207. const json = geojsonFormat.writeGeometryObject(geometry, {
  208. dataProjection: "EPSG:4326",
  209. featureProjection: this.kmap.map.getView().getProjection(),
  210. });
  211. polygonGeometries.push(json);
  212. });
  213. if (!polygonGeometries.length) return;
  214. const multiPolygonCoords = [];
  215. polygonGeometries.forEach((geom) => {
  216. if (!geom) return;
  217. if (geom.type === "Polygon") {
  218. multiPolygonCoords.push(geom.coordinates);
  219. } else if (geom.type === "MultiPolygon") {
  220. geom.coordinates.forEach((coords) => multiPolygonCoords.push(coords));
  221. }
  222. });
  223. if (!multiPolygonCoords.length) return;
  224. const farmPolygon = turf.multiPolygon(multiPolygonCoords);
  225. const bbox = turf.bbox(farmPolygon);
  226. const squareGrid = turf.squareGrid(bbox, this.gridSideKm, { units: "kilometers" });
  227. if (!squareGrid?.features?.length) return;
  228. squareGrid.features.forEach((gridFeature, index) => {
  229. let clipped = null;
  230. try {
  231. clipped = turf.intersect(gridFeature, farmPolygon);
  232. } catch (_) {
  233. try {
  234. // 兼容 turf 不同版本的 intersect 入参
  235. clipped = turf.intersect(turf.featureCollection([gridFeature, farmPolygon]));
  236. } catch (e) {
  237. clipped = null;
  238. }
  239. }
  240. if (!clipped) return;
  241. const geometryObj = clipped.geometry;
  242. if (!geometryObj) return;
  243. const olGeometry = geojsonFormat.readGeometry(geometryObj, {
  244. dataProjection: "EPSG:4326",
  245. featureProjection: this.kmap.map.getView().getProjection(),
  246. });
  247. if (!olGeometry) return;
  248. const cell = new Feature({ geometry: olGeometry });
  249. cell.set("gridId", `grid-${index}`);
  250. cell.set("selected", false);
  251. this.gridLayer.source.addFeature(cell);
  252. });
  253. }
  254. }
  255. export default EditMap;