吉安感知网项目-后端
linwei
2026-06-05 f3104f14213028277c883e19301b820ae724bd70
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package org.sxkj.common.utils;
 
import org.apache.commons.lang3.StringUtils;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
 
public class GeomUtils {
 
    private static final GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
    private static final WKTReader wktReader = new WKTReader(geometryFactory);
 
    public static boolean isGeomInvalid(String geom) {
        if (StringUtils.isBlank(geom)) {
            return false;
        }
        String upper = geom.trim().toUpperCase();
        return !upper.contains("POLYGON");
    }
 
    /**
     * 验证并转换几何数据,确保其有效
     * @param geom WKT格式的几何数据
     * @return 有效的几何数据,或null如果转换失败
     */
    public static String validateAndFormatGeom(String geom) {
        if (StringUtils.isBlank(geom)) {
            return null;
        }
 
        try {
            // 解析WKT字符串
            Geometry geometry = wktReader.read(geom);
 
            // 如果几何数据无效,尝试修复
            if (!geometry.isValid()) {
                geometry = geometry.buffer(0);
            }
 
            // 确保几何数据有效
            if (geometry.isValid()) {
                return geometry.toText();
            } else {
                return null;
            }
        } catch (ParseException e) {
            // 解析失败
            return null;
        }
    }
 
    /**
     * 从几何数据中提取中心点坐标
     * 
     * @param geom WKT格式的几何数据
     * @return 中心点坐标数组,格式为 [经度, 纬度],如果提取失败返回null
     */
    public static double[] extractCenterPoint(String geom) {
        if (StringUtils.isBlank(geom)) {
            return null;
        }
 
        try {
            // 解析WKT字符串
            Geometry geometry = wktReader.read(geom);
 
            // 获取几何对象的中心点
            Point centroid = geometry.getCentroid();
            if (centroid == null) {
                return null;
            }
 
            Coordinate coordinate = centroid.getCoordinate();
            if (coordinate == null) {
                return null;
            }
 
            // 返回 [经度, 纬度]
            return new double[]{coordinate.x, coordinate.y};
        } catch (ParseException e) {
            return null;
        }
    }
}