puzhibing
2026-03-13 d4f8d30d1c6e4397dbfbdbb759cc66132913dd53
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
package com.xiaopeng.map.utils;
 
import lombok.extern.slf4j.Slf4j;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Polygon;
import org.springframework.stereotype.Component;
 
@Component
@Slf4j
public class PolygonOverlapService {
    
    /**
     * 检查两个多边形是否重叠
     * @param polygon1Points 多边形1的坐标点 "lng1_lat1,lng2_lat2,..."
     * @param polygon2Points 多边形2的坐标点 "lng1_lat1,lng2_lat2,..."
     * @return 是否重叠
     */
    public boolean checkPolygonOverlap(String polygon1Points, String polygon2Points) {
        try {
            Polygon polygon1 = createPolygonFromPoints(polygon1Points);
            Polygon polygon2 = createPolygonFromPoints(polygon2Points);
            
            // 使用 JTS 库判断多边形是否相交
            return polygon1.intersects(polygon2);
        } catch (Exception e) {
            log.error("多边形重叠检测失败", e);
            return false; // 发生错误时默认不重叠,可根据业务需要调整
        }
    }
    
    /**
     * 从坐标点字符串创建多边形
     * @param pointsStr 坐标点字符串 "lng1_lat1,lng2_lat2,lng3_lat3,..."
     * @return JTS Polygon 对象
     */
    private Polygon createPolygonFromPoints(String pointsStr) {
        if (!pointsStr.contains(",")) {
            throw new IllegalArgumentException("无效的坐标点格式");
        }
        
        String[] pointPairs = pointsStr.split(",");
        Coordinate[] coordinates = new Coordinate[pointPairs.length + 1]; // +1 是为了闭合多边形
        
        for (int i = 0; i < pointPairs.length; i++) {
            String[] lngLat = pointPairs[i].trim().split("_");
            if (lngLat.length != 2) {
                throw new IllegalArgumentException("坐标点格式错误: " + pointPairs[i]);
            }
            
            double lng = Double.parseDouble(lngLat[0]);
            double lat = Double.parseDouble(lngLat[1]);
            coordinates[i] = new Coordinate(lng, lat);
        }
        
        // 闭合多边形,最后一个点与第一个点相同
        coordinates[coordinates.length - 1] = coordinates[0];
        
        GeometryFactory geometryFactory = new GeometryFactory();
        LinearRing linearRing = geometryFactory.createLinearRing(coordinates);
        return geometryFactory.createPolygon(linearRing);
    }
}