Search code examples
androidgoogle-mapsgoogle-maps-android-api-2geofencingandroid-geofence

Android Maps Spherical Util Distance


I have a polyline with point A & B dropped on a map.

At present I am calculating the distance from the line from my location by using the

computeOffset()

and dropping points every five feet on that line and then looping through with the

computeDistanceBetween()

to find the nearest point.

Is there another method or classes out there for this because 5 ft is terribly far away when using an external GPS receiver. I could go to infinitesimally small increments but with the loop and point storage memory would be used up in no time.

Is there anything built into Android at the moment that supports automatic distance calculation from a line?


Solution

  • If you ignore the spherical nature of the surface, which should be o.k. for small distances, your location and the line are forming a triangle. The distance is just the height of this triangle. So you just need enough information about the triangle, e.g. the length of all sides, to calculate the height. The length of all sides is just the distance between the 3 points (your location and the two ends of the line). Call the side formed by your line A, and the other sides B and C. The height can be computed then as H=(2/A)sqrt[s(s-A)(s-B)(s-C)] with s=(1/2)(A+B+C) (Just looked up this formula. Did not try it.)

    EDIT

    The solution above gives the distance to the straight line defined as prolongation of your polyline, but without considering the endpoints. I guess you are looking for the distance to the line limited by its endpoints.

    Thus you need to find out in addition, whether the orthogonal projection of your location to the line lies within the endpoints or outside, or with other words, whether the angles between the triangle sides A and B or A and C are greater than 90 degrees. This can only be the case if B or C are longer than A. If so, take the shorter one (let' say its B) and check whether B*B + A*A is greater than C*C. (It follows from the law of cosines, that the angle is then greater than 90 degrees.) In this case, B is the distance you are looking for.