areaMap.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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 { Vector as VectorSource } from "ol/source.js";
  5. import { Point } from 'ol/geom';
  6. import { newPoint, newAreaFeature } from "@/utils/map";
  7. import { GeoJSON, WKT } from 'ol/format'
  8. import { Feature } from "ol";
  9. import { getArea } from "ol/sphere"
  10. import * as turf from "@turf/turf"
  11. import Style from "ol/style/Style";
  12. import Icon from "ol/style/Icon";
  13. import { Fill, Text, Stroke } from "ol/style";
  14. import Overlay from "ol/Overlay";
  15. import * as proj from "ol/proj";
  16. import { buffer as bufferExtent, getWidth, getHeight } from "ol/extent";
  17. import proj4 from "proj4"
  18. import { register } from "ol/proj/proj4";
  19. 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");
  20. register(proj4);
  21. /**
  22. *
  23. */
  24. class AreaMap {
  25. constructor() {
  26. this.labelOverlays = [];
  27. this.gardenPolygonLayer = new KMap.VectorLayer("gardenPolygonLayer", 999, {
  28. minZoom: 8,
  29. maxZoom: 22,
  30. source: new VectorSource({}),
  31. style: (f) => this.getZoneStyle(f),
  32. });
  33. // 位置图标
  34. this.clickPointLayer = new KMap.VectorLayer("clickPointLayer", 9999, {
  35. style: (f) => {
  36. let pointIcon = new Style({
  37. image: new Icon({
  38. src: require("@/assets/img/home/garden-point.png"),
  39. scale: 0.5,
  40. anchor: [0.5, 1],
  41. }),
  42. });
  43. let nameText = new Style({
  44. text: new Text({
  45. font: "14px sans-serif",
  46. text: f.get("name"),
  47. offsetY: 10,
  48. fill: new Fill({ color: "#fff" }), // 字体颜色
  49. stroke: new Stroke({
  50. color: "#000",
  51. width: 0.5,
  52. }),
  53. }),
  54. });
  55. return [pointIcon, nameText]
  56. },
  57. });
  58. }
  59. getZoneStyle(f) {
  60. const flySpeed = f.get("fly_speed");
  61. const labelStyle = f.get("label_style") || (flySpeed ? "card" : "legacy");
  62. const fillColor = f.get("fill_color") || "#00000080";
  63. const strokeColor = f.get("stroke_color") || "#2199F8";
  64. const zoneName = f.get("zone_name") || (f.get("mianji") ? `${f.get("mianji")}亩` : "");
  65. const styles = [
  66. new Style({
  67. fill: new Fill({ color: fillColor }),
  68. stroke: new Stroke({ color: strokeColor, width: 2 }),
  69. }),
  70. ];
  71. if (!zoneName) return styles;
  72. if (labelStyle === "legacy") {
  73. styles.push(
  74. new Style({
  75. text: new Text({
  76. font: "14px sans-serif",
  77. text: zoneName,
  78. offsetY: 10,
  79. fill: new Fill({ color: "#fff" }),
  80. stroke: new Stroke({
  81. color: "#000",
  82. width: 0.5,
  83. }),
  84. }),
  85. })
  86. );
  87. return styles;
  88. }
  89. if (labelStyle === "simple") {
  90. styles.push(
  91. new Style({
  92. text: new Text({
  93. text: zoneName,
  94. font: "13px sans-serif",
  95. fill: new Fill({ color: "#ffffff" }),
  96. backgroundFill: new Fill({ color: "rgba(80, 80, 80, 0.85)" }),
  97. padding: [4, 8, 4, 8],
  98. }),
  99. })
  100. );
  101. return styles;
  102. }
  103. return styles;
  104. }
  105. createZoneCardLabelElement(zoneName, flySpeed) {
  106. const wrap = document.createElement("div");
  107. Object.assign(wrap.style, {
  108. background: "#ffffff",
  109. borderRadius: "4px",
  110. padding: "6px 10px",
  111. boxShadow: "0 1px 4px rgba(0, 0, 0, 0.08)",
  112. textAlign: "center",
  113. pointerEvents: "none",
  114. whiteSpace: "nowrap",
  115. });
  116. const title = document.createElement("div");
  117. title.textContent = zoneName;
  118. Object.assign(title.style, {
  119. fontSize: "13px",
  120. fontWeight: "600",
  121. color: "#262626",
  122. lineHeight: "18px",
  123. });
  124. wrap.appendChild(title);
  125. if (flySpeed) {
  126. const sub = document.createElement("div");
  127. sub.textContent = `飞巡速度:${flySpeed}`;
  128. Object.assign(sub.style, {
  129. fontSize: "11px",
  130. color: "#999999",
  131. lineHeight: "16px",
  132. marginTop: "2px",
  133. });
  134. wrap.appendChild(sub);
  135. }
  136. return wrap;
  137. }
  138. clearLabelOverlays() {
  139. if (!this.labelOverlays?.length || !this.kmap?.map) return;
  140. this.labelOverlays.forEach((overlay) => {
  141. this.kmap.map.removeOverlay(overlay);
  142. });
  143. this.labelOverlays = [];
  144. }
  145. syncLabelOverlays() {
  146. this.clearLabelOverlays();
  147. if (!this.kmap?.map || !this.gardenPolygonLayer?.source) return;
  148. this.gardenPolygonLayer.source.getFeatures().forEach((f) => {
  149. const flySpeed = f.get("fly_speed");
  150. const labelStyle = f.get("label_style") || (flySpeed ? "card" : "legacy");
  151. if (labelStyle !== "card") return;
  152. const zoneName = f.get("zone_name");
  153. if (!zoneName) return;
  154. const geom = f.getGeometry();
  155. if (!geom?.getInteriorPoint) return;
  156. const coord = geom.getInteriorPoint().getCoordinates();
  157. const overlay = new Overlay({
  158. element: this.createZoneCardLabelElement(zoneName, flySpeed),
  159. position: coord,
  160. positioning: "center-center",
  161. stopEvent: false,
  162. });
  163. this.kmap.map.addOverlay(overlay);
  164. this.labelOverlays.push(overlay);
  165. });
  166. }
  167. initMap(location, target, options = {}) {
  168. const { interactive = false } = options;
  169. let level = 16;
  170. let coordinate = util.wktCastGeom(location).getFirstCoordinate();
  171. // dragPan / mouseWheelZoom 需在 Map 构造时传入,interactive 为 true 时才能拖拽与缩放
  172. this.kmap = new KMap.Map(
  173. target,
  174. level,
  175. coordinate[0],
  176. coordinate[1],
  177. null,
  178. 8,
  179. 22,
  180. undefined,
  181. interactive,
  182. interactive
  183. );
  184. if (!interactive && this.kmap?.map) {
  185. this.kmap.map.getInteractions().forEach((i) => i.setActive(false));
  186. }
  187. let xyz2 = config.base_img_url3 + "map/lby/{z}/{x}/{y}.png";
  188. this.kmap.addXYZLayer(xyz2, { minZoom: 8, maxZoom: 22 }, 2);
  189. this.kmap.addLayer(this.gardenPolygonLayer.layer);
  190. this.kmap.addLayer(this.clickPointLayer.layer);
  191. }
  192. initLayer(rangeWkt) {
  193. if (!rangeWkt) {
  194. this.initZones([]);
  195. return;
  196. }
  197. this.initZones([{ zone_geometry: rangeWkt }]);
  198. }
  199. /** @param {{ zone_geometry?: string, zone_name?: string, fly_speed?: string, fill_color?: string, stroke_color?: string, label_style?: 'card'|'simple' }[]} zones */
  200. initZones(zones) {
  201. this.clearLabelOverlays();
  202. if (this.gardenPolygonLayer.source) {
  203. this.gardenPolygonLayer.source.clear();
  204. }
  205. if (this.clickPointLayer.source) {
  206. this.clickPointLayer.source.clear();
  207. }
  208. const list = Array.isArray(zones) ? zones : [];
  209. const seen = new Set();
  210. list.forEach((zone) => {
  211. const wkt =
  212. typeof zone?.zone_geometry === "string"
  213. ? zone.zone_geometry.trim()
  214. : "";
  215. if (!wkt || seen.has(wkt)) return;
  216. seen.add(wkt);
  217. try {
  218. const f = newAreaFeature({ geomWkt: wkt }, "geomWkt");
  219. f.set("zone_name", zone.zone_name ?? "");
  220. if (zone.fly_speed) f.set("fly_speed", zone.fly_speed);
  221. if (zone.fill_color) f.set("fill_color", zone.fill_color);
  222. if (zone.stroke_color) f.set("stroke_color", zone.stroke_color);
  223. if (zone.label_style) f.set("label_style", zone.label_style);
  224. this.gardenPolygonLayer.source.addFeature(f);
  225. } catch (e) {
  226. console.warn("[AreaMap] zone_geometry parse failed", e);
  227. }
  228. });
  229. this.syncLabelOverlays();
  230. this.fitView();
  231. }
  232. /**
  233. * 调整地图视图以适应地块范围
  234. */
  235. fitView() {
  236. if (!this.kmap?.map) return;
  237. const map = this.kmap.map;
  238. map.updateSize();
  239. let extent = this.gardenPolygonLayer.source.getExtent();
  240. if (!extent || !Number.isFinite(extent[0])) return;
  241. const ew = getWidth(extent);
  242. const eh = getHeight(extent);
  243. if (ew <= 0 || eh <= 0) return;
  244. // 略外扩,避免描边贴边、视觉上像被裁切
  245. extent = bufferExtent(extent, Math.max(ew, eh) * 0.04);
  246. const size = map.getSize();
  247. if (!size || size[0] < 4 || size[1] < 4) return;
  248. const [sw, sh] = size;
  249. // padding 不能过大:小高度容器里固定 80 会导致内框高度为负,地块无法完整显示
  250. let padX = Math.max(8, Math.min(48, Math.floor(sw * 0.1)));
  251. let padY = Math.max(8, Math.min(48, Math.floor(sh * 0.1)));
  252. let padTop = Math.min(sh - padY - 4, padY + 14);
  253. let padBottom = padY;
  254. let padLeft = padX;
  255. let padRight = padX;
  256. if (padTop + padBottom >= sh - 2) {
  257. const p = Math.max(4, Math.floor(sh / 6));
  258. padTop = padBottom = p;
  259. }
  260. if (padLeft + padRight >= sw - 2) {
  261. const p = Math.max(4, Math.floor(sw / 6));
  262. padLeft = padRight = p;
  263. }
  264. this.kmap.getView().fit(extent, {
  265. size,
  266. duration: 80,
  267. padding: [padTop, padRight, padBottom, padLeft],
  268. maxZoom: 22,
  269. });
  270. }
  271. fitByGardenId(gardenId, hasMapAnimate) {
  272. this.gardenPolygonLayer.source.forEachFeature((f) => {
  273. if (f.get("organId") == gardenId) {
  274. const extent = f.getGeometry().getExtent()
  275. this.kmap.getView().fit(extent, { padding: [60, 60, 60, 60], duration: hasMapAnimate ? 1500 : 0 });
  276. const currentZoom = this.kmap.getView().getZoom();
  277. if (currentZoom > 16) {
  278. // this.kmap.getView().setZoom(16);
  279. this.kmap.getView().animate({
  280. zoom: 16,
  281. duration: hasMapAnimate ? 1500 : 0 // 动画持续时间,单位为毫秒
  282. });
  283. }
  284. }
  285. })
  286. }
  287. destroyMap() {
  288. this.clearLabelOverlays();
  289. if (this.gardenPolygonLayer?.source) {
  290. this.gardenPolygonLayer.source.clear();
  291. }
  292. if (this.clickPointLayer?.source) {
  293. this.clickPointLayer.source.clear();
  294. }
  295. if (this.kmap && typeof this.kmap.destroy === "function") {
  296. this.kmap.destroy();
  297. }
  298. this.kmap = null;
  299. }
  300. }
  301. export default AreaMap;