2012-06-13 80 views
0

我有这个JavaScript代码,它需要一个位置列表,并根据用户位置重新排列列表项。我如何更改代码,使其只显示1KM附近的位置,而不是仅对整个列表重新排序。位置感知

<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 filterList(){ 
    $('ol li').each(function(){ 
     if($(this).data('distance') > 1){ 
     $(this).remove(); 
     } 
    }); 
} 

代替上述解决方案,你可以做以下?

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