Reputation: 560
I have a region defined by a set List of geopoints and I need to know if a coordinate is inside this region
public class Region{
List<Coordinate> boundary;
}
public class Coordinate{
private double latitude;
private double longitude;
}
public static boolean isInsideRegion(Region region, Coordinate coordinate){
}
Upvotes: 7
Views: 7656
Reputation: 85779
You can apply a Point in polygon algorithm from the Computational Geometry set of problems.
There are four algorithms written in C by Paul Bourke, you can see the code here. There is an adaptation to Java in a Processing Forum, just in case you can't use 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;
}
}
Upvotes: 11
Reputation: 29646
Use Path2D
to construct the region boundary shape. Then, create an Area
using the Path2D
and you can query contains
quickly to determine whether your points are contained in the area. :-)
/* 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(...)) {
...
}
Note: there is little reason to roll your own Region
and Coordinate
classes for what the Java geometry classes provide. I suggest you abandon Coordinate
(which is technically a misnomer as it's actually a pair of graticular coordinates) in favor of Point2D
.
Note that there is a Polygon
class, though it is tailored towards actual use for graphics and a relic of the past. It only supports int
coordinates, which likely won't do you any good when using geopoints!
Upvotes: 5