5

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!

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
jheimbouch
  • 969
  • 8
  • 20

2 Answers2

3

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.

jbx
  • 21,365
  • 18
  • 90
  • 144
  • I am using the Location.distanceTo function to find the distance in other bits of code, but I don't see where that applies in this formula. Is there something I am missing? – jheimbouch Feb 11 '13 at 00:52
  • This formula is just a generic formula you can use if you have the longitude and lattitude as numeric values. The `Location.distanceTo()` is in fact doing the same thing internally as you can see here: http://developer.android.com/reference/android/location/Location.html#distanceTo(android.location.Location). So you can use either that or implement it manually yourself. – jbx Feb 11 '13 at 01:08
  • Using the Location.distanceTo is used for one location to another location. I am wanting a way to calculate one location to another location that exists on a line segment. However, the only points I know for the line segment are the start and endpoints. Sorry if I mislead the problem. – jheimbouch Feb 11 '13 at 01:11
  • OK, if you check that link there are several variations. Check out the cross-track distance one I think it suits your needs. – jbx Feb 11 '13 at 01:21
2

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.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127