Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the distance from point A to line segment using Lat /Lon

I am working on an Android app that uses the GPS. I would like to know if there is a way I can throw out GPS Location data if the "new location" (point C) is too far away from line segment AB. I am using the Point to Line Segment formula found on Wikipedia.

So far, the code I have is returning NaN when I try to use Latitude and Longitude coordinates.

private void verifyGPSLocation(Location start, Location end, Location current){
    final double errorValue = 0.0000216;
    double normalLength = Math.hypot(end.getLatitude() - start.getLatitude(), end.getLongitude() - start.getLongitude());
    double ret = Math.abs(((current.getLatitude() - start.getLatitude()) * (end.getLongitude() - start.getLongitude()) - (end.getLatitude() - start.getLatitude()))/normalLength );
    Log.e("Coooooord", normalLength+"--"+ret);
}

This is my first post so please let me know if I have not done this correctly or with enough information. Thanks for your help, I love this site!

like image 650
jheimbouch Avatar asked Feb 11 '13 00:02

jheimbouch


People also ask

How do you find the distance between a point and a line segment?

The distance from (x0, y0) to this line is measured along a vertical line segment of length |y0 − (− c/b)| = |by0 + c|/|b| in accordance with the formula. Similarly, for vertical lines (b = 0) the distance between the same point and the line is |ax0 + c|/|a|, as measured along a horizontal line segment.

How do you calculate distance using lat and long?

For this divide the values of longitude and latitude of both the points by 180/pi. The value of pi is 22/7. The value of 180/pi is approximately 57.29577951. If we want to calculate the distance between two places in miles, use the value 3, 963, which is the radius of Earth.


2 Answers

I think the formula you are using to find the distance between 2 geographic points is too simplistic. Due to the curvature of the earth, the formula is a bit more complicated. Have a look here, this provides a more accurate approximation.

There is a Javascript example too, so you can easily change it to Java with a few syntactical tweaks.

After clarification, you seem to be looking for the distance of a point to a path on the earth between two locations. Check out the cross-track distance variation in the link above.

like image 123
jbx Avatar answered Sep 30 '22 02:09

jbx


Your distance algorithm is wrong. It doesn't account for the curvature of the Earth- lines of longitude are closer at higher latitudes, further at lower ones. Use the Location.distanceTo function.

like image 22
Gabe Sechan Avatar answered Sep 30 '22 01:09

Gabe Sechan