我有一个由一组地理位置定义的区域,我需要知道一个坐标是否在这个区域内
public class Region{
List<Coordinate> boundary;
}
public class Coordinate{
private double latitude;
private double longitude;
}
public static boolean isInsideRegion(Region region, Coordinate coordinate){
}
Run Code Online (Sandbox Code Playgroud)
Lui*_*oza 11
您可以从Computational Geometry问题集中应用Point in polygon算法.
Paul Bourke用C语言编写了四种算法,你可以在这里看到代码.在处理论坛中对Java进行了改编,以防您无法使用Java7:
public class RegionUtil {
boolean coordinateInRegion(Region region, Coordinate coord) {
int i, j;
boolean isInside = false;
//create an array of coordinates from the region boundary list
Coordinate[] verts = (Coordinate)region.getBoundary().toArray(new Coordinate[region.size()]);
int sides = verts.length;
for (i = 0, j = sides - 1; i < sides; j = i++) {
//verifying if your coordinate is inside your region
if (
(
(
(verts[i].getLongitude() <= coord.getLongitude()) && (coord.getLongitude() < verts[j].getLongitude())
) || (
(verts[j].getLongitude() <= coord.getLongitude()) && (coord.getLongitude() < verts[i].getLongitude())
)
) &&
(coord.getLatitude() < (verts[j].getLatitude() - verts[i].getLatitude()) * (coord.getLongitude() - verts[i].getLongitude()) / (verts[j].getLongitude() - verts[i].getLongitude()) + verts[i].getLatitude())
) {
isInside = !isInside;
}
}
return isInside;
}
}
Run Code Online (Sandbox Code Playgroud)
使用Path2D
构造区域边界形状。然后,Area
使用创建一个Path2D
,您可以contains
快速查询以确定您的点是否包含在该区域中。:-)
/* assuming a non-zero winding rule */
final Path2D boundary = new Path2D.Double();
/* initialize the boundary using moveTo, lineTo, quadTo, etc. */
final Area area = new Area(boundary);
...
/* test for whether a point is inside */
if (area.contains(...)) {
...
}
Run Code Online (Sandbox Code Playgroud)
注意:没有什么理由可以为Java几何类提供自己的类Region
和Coordinate
类。我建议您放弃Coordinate
(因为它实际上是一对刻度坐标,因此从技术上来说是个误称)Point2D
。
注意这里是一个Polygon
类,但它是迈向显卡实际使用和过去的遗迹定制。它仅支持int
坐标,使用地理点时可能对您没有任何帮助!
归档时间: |
|
查看次数: |
6539 次 |
最近记录: |