2015-04-03 39 views
0

我正在開發一個簡單的jQuery/Phonegap應用程序,我正在使用watchPosition來持續計算當前距離和某個遠程位置之間的距離。這工作得很好,但這是我的問題。我想在距離該地點不到一英里時觸發一個事件(功能)。我現在擁有的方式只要距離不到一英里就會繼續觸發事件。我能做些什麼來「告訴」watchPosition只觸發一次事件並繼續觀看我的位置Phonegap watchPosition測量距離和觸發事件

我包括了我認爲的代碼的相關部分供您參考。 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(); 
} 

} 

距離計算功能:

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; 
} 

如果更多的代碼是必要的,請讓我知道。我還想對先前詢問的關於計算距離Link的這個問題給予肯定。謝謝!

+1

爲什麼你不使用varibale來確保你的這個事件在距離低於一英里時變得不相關? – Blauharley 2015-04-03 17:40:26

回答

2

只需使用一個標誌來跟蹤警報。

var alerFlag = true; 
if (distancia < 1 && alerFlag == true) { 
    alert('Almost There'); 
    playSound(); 
    alerFlag = false; 
}else{ 
    alerFlag = true; // This is for whenever you go greater than 1 mi 
}