OK, so I already have the answer to this question but it took me a long time to reach it so I thought I would share it, particularly since someone asked me but under an unrelated question
I created a Phonegap-based navigation app for guided walks that tracks the user's location around a predefined route using GPS. My routes have triggers placed at specific geo-locations around the route which give instructions to the user based on their current location. The problem is that GPS is not super accurate or reliable, so even though I allowed a "visiting radius" around those locations of around 20 metres, real-world testing resulted in those triggers sometimes being missed because a GPS position update would occur slightly before the user entered the visiting radius and slightly afterwards. I tried increasing the radius but this meant that the trigger fired too early to be relevant to the user's current position.
So how do I solve this in a way that works using “real-world” GPS data?
I stumbled upon this fantastic page by Movable Type of formulae for geospatial calculations. Even better, most of the formulae are already written in Javascript which was super-cool for my Phonegap app. However, the formula that caught my attention was this one for calculating the cross-track distance between two points. In terms of my app and real-world use, this means that even if the GPS updates are infrequent enough to miss the radius of my target location, I can calculate if the user visited the target based on the path between the most recent position and its predecessor.
EDIT 24/04/15: I've fixed a bug in the
constrainedCrossTrackDistance
function, so anyone using it should update their implementation to the one in this answer.The JS library didn’t include this formula, so I extended the Movable Type library to implement it:
However, real-world testing again showed this didn’t quite do the job. The problem was that this function was giving false positives because it didn’t take it into consideration the bounding box formed by the two end points and the radius. This led me to add a further function to constrain the crosstrack distance to within that bounding box:
This can then be used to determine if the target position has been visited in a real-world scenario:
Here's a fiddle illustrating a use case
It took me a long time and lot of testing to come up with this so I hope it can be of help to other people :-)