Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to implement point in polygon to the search #76

Open
xushaomin opened this issue Feb 2, 2018 · 2 comments
Open

how to implement point in polygon to the search #76

xushaomin opened this issue Feb 2, 2018 · 2 comments
Labels

Comments

@xushaomin
Copy link

how to implement point in polygon to the search!

@davidmoten
Copy link
Owner

davidmoten commented Feb 2, 2018

Search on the bounding box of the polygon then refine the returned results. If the polygon is a weird shape you might even choose to cover it with multiple bounding boxes to search more efficiently.

@DusonWang
Copy link

DusonWang commented Apr 8, 2018

@xushaomin
public boolean searchPoint(Point point) {

    if (CollectionUtils.isEmpty(corner)) {
        return false;
    }

    float x = point.x();
    float y = point.y();
    int points = corner.size();
    int hits = 0;
    float lastX = corner.get(points - 1).getPolyX();
    float lastY = corner.get(points - 1).getPolyY();
    float curX, curY;

    for (int i = 0; i < points; lastX = curX, lastY = curY, i++) {
        curX = corner.get(i).getPolyX();
        curY = corner.get(i).getPolyY();
        if (x == curX && y == curY) {
            return true;
        }

        if (curY == lastY) {
            continue;
        }

        float leftX;
        if (curX < lastX) {
            if (x >= lastX) {
                continue;
            }
            leftX = curX;
        } else {
            if (x >= curX) {
                continue;
            }
            leftX = lastX;
        }
        float test1, test2;
        if (curY < lastY) {
            if (y < curY || y >= lastY) {
                continue;
            }
            if (x < leftX) {
                hits++;
                continue;
            }
            test1 = x - curX;
            test2 = y - curY;
        } else {
            if (y < lastY || y >= curY) {
                continue;
            }
            if (x < leftX) {
                hits++;
                continue;
            }
            test1 = x - lastX;
            test2 = y - lastY;
        }

        if (test1 < (test2 / (lastY - curY) * (lastX - curX))) {
            hits++;
        }
    }
    return (hits & 1) != 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants