Newer
Older
dxcgt / app / src / main / java / com / smartdot / cgt / util / GisUtil.java
wangxitong on 6 Apr 2021 1 KB first commit
package com.smartdot.cgt.util;

import java.io.IOException;

import org.json.JSONException;

public abstract class GisUtil {

    private static double getX(double y, double x1, double y1, double x2, double y2) {
        return (((x1 - x2) * y) + ((x2 * y1) - (x1 * y2))) / (y1 - y2);
    }

    public static boolean isPointInPolygon(PointD point, PointD[] polygonPoints) {
        double px = point.x;
        double py = point.y;
        int numSeg = polygonPoints.length - 1;
        PointD start, end;
        double x1, y1, x2, y2, cx;
        int crosses = 0;
        for (int i = 0; i < numSeg; ++i) {
            start = polygonPoints[i];
            x1 = start.x;
            y1 = start.y;
            end = polygonPoints[i + 1];
            x2 = end.x;
            y2 = end.y;
            if (y1 == y2) {
                if (py == y1) {
                    if (x1 <= x2 && (px >= x1 && px <= x2) || x1 >= x2 && (px <= x1 && px >= x2)) {
                        crosses = -1;
                        break;
                    }
                }
                continue;
            }
            cx = (double) getX(py, x1, y1, x2, y2);
            if (cx == px) {
                if (y1 < y2 && (py >= y1 && py <= y2) || y1 > y2 && (py <= y1 && py >= y2)) {
                    crosses = -1;
                    break;
                }
            }
            if (cx <= px) {
                continue;
            }
            if (x1 != x2 && (cx < Math.min(x1, x2) || cx > Math.max(x1, x2))) {
                continue;
            }
            if (y1 < y2 && (py >= y1 && py < y2) || y1 > y2 && (py < y1 && py >= y2)) {
                ++crosses;
            }
        }
        boolean contained = (crosses & 1) == 1;
        return contained;
    }

    public abstract void queryFeature(String url) throws IOException, JSONException;
}