Java - 如何检查lat / lng坐标是否在多边形内

时间:2018-03-18 16:48:06

标签: java polygon

我想检查地图上的给定点(其纬度和经度)是否在某个多边形内。我有多边形的顶点坐标(在lat / long中)。

我想过创建一个Polygon并检查点是否在里面,但是它让我觉得这个点总是在外面......也许多边形不适用于地理参考坐标?

Double[] xCoords = {40.842226, 40.829498, 40.833394, 40.84768, 40.858716}
Double[] yCoords = {14.211753, 14.229262, 14.26617, 14.278701,  14.27715}
Double[] myPoint = {40.86141, 14.279932};


Path2D myPolygon = new Path2D.Double();
            myPolygon.moveTo(xCoords[0], yCoords[0]); //first point
            for(int i = 1; i < xCoords.length; i ++) {
                myPolygon.lineTo(xCoords[i], yCoords[i]); //draw lines
            }
            myPolygon.closePath(); //draw last line

               if(myPolygon.contains(myPoint{0}, myPoint{1})) {
                //it's inside;
}

这就是谷歌地图中的样子

enter image description here

它总是返回false ...但是它在多边形内部......

2 个答案:

答案 0 :(得分:2)

无论多边形的形状如何,该点都不能包含在该多边形中。

您的最右侧坐标位于40.858716,而该点的x值为40.86141,这意味着该点位于多边形的右侧。 y相同,多边形中的最大y坐标为14.278701,而点为14.279932。这意味着该点之外。

此外,您正在反转坐标,我们心爱的城市的坐标为40.8518° N, 14.2681° E,这意味着40y14 { {1}}。

x会做得很好。我的观察只是告诉你,该点不在多边形中,但检查极值不是验证点是否在多边形内的一般解决方案。

答案 1 :(得分:0)

public class CoordinatesDTO {


private Long id;


private double latitude;


private double longnitude;

}

public static boolean isLocationInsideTheFencing(CoordinatesDTO location, List<CoordinatesDTO> fencingCoordinates) { //this is important method for Checking the point exist inside the fence or not.
    boolean blnIsinside = false;

    List<CoordinatesDTO> lstCoordinatesDTO = fencingCoordinates;

    Path2D myPolygon = new Path2D.Double();
    myPolygon.moveTo(lstCoordinatesDTO.get(0).getLatitude(), lstCoordinatesDTO.get(0).getLongnitude()); // first
                                                                                                        // point
    for (int i = 1; i < lstCoordinatesDTO.size(); i++) {
        myPolygon.lineTo(lstCoordinatesDTO.get(i).getLatitude(), lstCoordinatesDTO.get(i).getLongnitude()); // draw
                                                                                                            // lines
    }
    myPolygon.closePath(); // draw last line

    // myPolygon.contains(p);
    Point2D P2D2 = new Point2D.Double();
    P2D2.setLocation(location.getLatitude(), location.getLongnitude());

    if (myPolygon.contains(P2D2)) {
        blnIsinside = true;
    } else {
        blnIsinside = false;
    }

    return blnIsinside;
}