[英]Java - How to check if a lat/lng coords are inside a 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;
}
这是它在谷歌地图中的样子
它总是返回 false ...但是它在多边形内部的点...
无论多边形具有什么形状,该点都不可能包含在该多边形中。
您最右边的坐标是40.858716
而该点的 x 值为40.86141
,这意味着该点位于多边形的右侧。 y 也一样,多边形中的最大 y 坐标为14.278701
,而点位于14.279932
。 这意味着该点在外部。
此外,您正在反转坐标,我们心爱的城市的坐标是40.8518° N, 14.2681° E
,这意味着40
是y
, 14
是x
。
Path2D
会做的很好。 我的观察只是告诉您该点不在多边形中,但检查极值并不是验证点是否在多边形内的通用解决方案。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.