I'm developing a simple jQuery / Phonegap app and I'm using watchPosition to constantly calculate between the distance current location and some remote place. This works just fine, but this is my issue. I would like to trigger an event (function) when the distance is less than a mile from that location. The way I have it right now it would continue triggering the event as long as the distance is less than a mile. What can I do to "tell" watchPosition to trigger the event only once and continue watching my position?
I included what I consider the relevant part of the code for your reference.
Success portion of watchPosition:
var remoteLat = xx.xxxx;
var remoteLng = xx.xxxx;
function onSuccess(position) {
var myLat = position.coords.latitude;
var myLng = position.coords.longitude;
var distancia = gps_distance(myLat, myLng, remoteLat, remoteLng);
if (distancia < 1) {
alert('Almost There');
playSound();
}
}
Distance calculating function:
function gps_distance(lat1, lon1, lat2, lon2) {
var R = 3959; // use 3959 for miles or 6371 for km
var dLat = (lat2 - lat1) * (Math.PI / 180);
var dLon = (lon2 - lon1) * (Math.PI / 180);
var lat1 = lat1 * (Math.PI / 180);
var lat2 = lat2 * (Math.PI / 180);
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
If more of the code is necessary, please let me know. I also would like to give credit to this question previously asked about calculating distances Link . Thanks!