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){
}
Latitudes are horizontal lines that measure distance north or south of the equator. Longitudes are vertical lines that measure east or west of the meridian in Greenwich, England. Together, latitude and longitude enable cartographers, geographers and others to locate points or places on the globe.
The numbers are in decimal degrees format and range from -90 to 90 for latitude and -180 to 180 for longitude. For example, Washington DC has a latitude 38.8951 and longitude -77.0364 .
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;
}
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With