I came across this fantastic page on Movable Type Formulas for Geospatial Computing. Moreover, most of the formulas are already written in Javascript , which was super-cool for my Phonegap application. However, the formula that caught my attention was this one for calculating the distance between tracks between two points. As for my application and use in the real world, this means that even if GPS updates are not uncommon to skip the radius of my target location, I can calculate whether the user visited the target based on the path between the last position and its predecessor.
EDIT 24/04/15: I fixed the error in the constrainedCrossTrackDistance function, so anyone who uses it should update their implementation to the one in this answer.
The JS library did not include this formula, so I expanded the Movable Type library to implement it:
LatLon.prototype.crossTrackDistance = function(startPoint, endPoint, precision){ var R = this._radius; var d13 = startPoint.distanceTo(this, 10); var b13 = startPoint.bearingTo(this).toRad(); var b12 = startPoint.bearingTo(endPoint).toRad(); var d = Math.asin(Math.sin(d13/R)*Math.sin(b13-b12)) * R; return d.toPrecisionFixed(precision); }
However, testing in the real world again showed that this did not quite do the job. The problem was that this function gave false positives because it did not take into account its bounding box formed by two endpoints and a radius. This made me add another function to limit the cross-track distance within this bounding box:
LatLon.prototype.constrainedCrossTrackDistance = function(startPoint, endPoint, precision){ var bAB = startPoint.bearingTo(endPoint); var bAB_plus_90 = Geo.adjustBearing(bAB, 90); var bAB_minus_90 = Geo.adjustBearing(bAB, -90); var bAC = startPoint.bearingTo(this); var bBC = endPoint.bearingTo(this); var dAC = startPoint.distanceTo(this, 10); var dBC = endPoint.distanceTo(this, 10); if(Geo.differenceInBearings(bAC, bBC) > 90 && ((bBC > bAB_plus_90 && bAC < bAB_plus_90) || (bAC > bAB_minus_90 && bBC < bAB_minus_90))){ return Math.abs(this.crossTrackDistance(startPoint, endPoint, precision)); }else if((bBC < bAB_plus_90 && bAC < bAB_plus_90) || (bBC > bAB_minus_90 && bAC > bAB_minus_90)){ return Math.abs(dBC); }else if((bBC > bAB_plus_90 && bAC > bAB_plus_90) || (bBC < bAB_minus_90 && bAC < bAB_minus_90)){ return Math.abs(dAC); }else{ return (Math.abs(dBC) < Math.abs(dAC) ? Math.abs(dBC) : Math.abs(dAC)); } }
This can then be used to determine if the target position has been visited in the real scenario:
// Calculate if target location visited if( currentPos.distanceTo(targetPos)*1000 < tolerance || (prevPos && Math.abs(targetPos.constrainedCrossTrackDistance(prevPos, currentPos)*1000) < tolerance) ){ visited = true; }else{ visited = false; }
Here is a script illustrating a usage example
It took me a lot of time and a lot of testing to come up with this, so I hope this can help other people :-)