package com.njzscloud.supervisory.gps;

import java.util.List;

/**
 * 地理工具类，用于判断经纬度点是否在多边形区域内
 */
public class GeoUtils {

    /**
     * 判断点是否在多边形内
     *
     * @param point   待判断的点 [纬度, 经度]
     * @param polygon 多边形顶点列表，每个顶点为 [纬度, 经度]
     * @return 如果点在多边形内返回true，否则返回false
     */
    public static boolean isPointInPolygon(double[] point, List<double[]> polygon) {
        // 点的纬度和经度
        double lat = point[0];
        double lon = point[1];
        boolean inside = false;

        // 遍历多边形的每条边
        for (int i = 0, j = polygon.size() - 1; i < polygon.size(); j = i++) {
            double[] vertexI = polygon.get(i);
            double[] vertexJ = polygon.get(j);

            double latI = vertexI[0];
            double lonI = vertexI[1];
            double latJ = vertexJ[0];
            double lonJ = vertexJ[1];

            // 检查点是否在边的端点上
            if ((lat == latI && lon == lonI) || (lat == latJ && lon == lonJ)) {
                return true;
            }

            // 检查射线是否与当前边相交
            if (((latI > lat) != (latJ > lat)) &&
                    (lon < (lonJ - lonI) * (lat - latI) / (latJ - latI) + lonI)) {
                inside = !inside;
            }
        }

        return inside;
    }
}
