Skip to content

Instantly share code, notes, and snippets.

@makiftutuncu
Created September 5, 2016 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save makiftutuncu/7100d8ca2ba27a0ef6b2156ac5e2b77d to your computer and use it in GitHub Desktop.
Save makiftutuncu/7100d8ca2ba27a0ef6b2156ac5e2b77d to your computer and use it in GitHub Desktop.
Calculates the distance of a location point to the line constructed by other 2 location points and checks whether or not the location point is close enough to the line to be on it
/* If the distance between location point and line is less than this, point is considered to be on the line */
public static final double POINT_DISTANCE_TO_LINE_THRESHOLD = 0.01;
/* Calculates the distance of a location point to the line constructed by other 2 location points */
public double distanceOfPointToTheLine(Location location, Location point1, Location point2) {
double x0 = location.getLatitude();
double y0 = location.getLongitude();
double x1 = point1.getLatitude();
double y1 = point1.getLongitude();
double x2 = point2.getLatitude();
double y2 = point2.getLongitude();
double a = y2 - y1;
double b = x1 - x2;
double c = (x2 * y1) - (x1 * y2);
return Math.abs((a * x0) + (b * y0) + c) / Math.sqrt((a * a) + (b * b));
}
/* Checks whether or not the location point is close enough to the line constructed by other 2 location points to be on it */
public boolean isPointCloseToOrOnTheLine(Location location, Location point1, Location point2) {
return distanceOfPointToTheLine(location, point1, point2) <= POINT_DISTANCE_TO_LINE_THRESHOLD;
}
@makiftutuncu
Copy link
Author

Assume Location type to have latitude and longitude as double values accessible via getLatitude() and getLongitude() methods respectively.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment