2012-06-13 4 views
0

위치 목록을 사용하고 사용자 위치에 따라 목록 항목을 재정렬하는 자바 스크립트 코드가 있습니다. 전체 목록을 재정렬하는 대신 1KM 부근의 위치 만 표시하도록 코드를 어떻게 바꿀 수 있습니까? 당신은 다음과 같은 작업을 수행 할 수위치 인식

function filterList(){ 
    $('ol li').each(function(){ 
     if($(this).data('distance') > 1){ 
     $(this).remove(); 
     } 
    }); 
} 

대신 위의 솔루션 :

<script type="text/javascript"> 
$(document).bind("mobileinit", function() { 
$.mobile.ajaxEnabled = false; 
}); 
</script> 
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script> 
<script> 
function findMe() { 
if (navigator.geolocation != undefined) { 
navigator.geolocation.watchPosition(onFound, onError); 
} 
} 
function onFound(pos) { 
var userLat = pos.coords.latitude; 
var userLong = pos.coords.longitude; 
$('ol li').each(function (index) { 
var locationLat = $(this).find('.lat').html(); 
var locationLong = $(this).find('.long').html(); 
var distance = getDistance(userLat, locationLat, userLong, locationLong); 
$(this).data("distance", distance); 
}) 

reOrder(); 
} 

function onError(pos) { 
alert("Something Went wrong"); 
} 

function reOrder() { 
$('ol li').sort(sortAlpha).appendTo('ol'); 
} 

function sortAlpha(a, b) { 
return $(a).data('distance') > $(b).data('distance') ? 1 : -1; 
}; 

function getDistance(lat1, lat2, lon1, lon2) { 
var R = 6371; // km 
var d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + 
Math.cos(lat1) * Math.cos(lat2) * 
Math.cos(lon2 - lon1)) * R; 
return d; 

}; 
</script> 

<style> 
ol .long, ol .lat 
{ 
display: none; 
} 
</style> 

답변

0

당신은 다음처럼 작성할 수 있습니까?

function onFound(pos) { 
    var userLat = pos.coords.latitude; 
    var userLong = pos.coords.longitude; 
    $('ol li').each(function (index) { 
     var locationLat = $(this).find('.lat').html(); 
     var locationLong = $(this).find('.long').html(); 
     var distance = getDistance(userLat, locationLat, userLong, locationLong); 
     if(Math.ceil(distance)>1){ 
     $(this).remove(); 
     } 
     else{ 
     $(this).data("distance", distance); 
     } 
    }); 
reOrder(); 
} 

filterList 기능을 제거 할 수 있습니다. 나는 그것이 당신을 위해 지금 일하기를 바랍니다.

+0

감사합니다. 코드에서 어디에서이 함수를 삽입합니까? – dbreezio

+0

이 함수는 어디에서나 사용할 수 있지만 reOrder 대신이 함수를 호출해야합니다. – emphaticsunshine

+0

reOrder 대신 해당 함수를 사용하려고 시도했지만 작동하지 않습니다. 네가 잘못 알고 있는게 있니? – dbreezio