首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >位置感知

位置感知
EN

Stack Overflow用户
提问于 2012-06-13 18:45:55
回答 1查看 118关注 0票数 0

我有这段javascript代码,它获取一个位置列表,并根据用户的位置重新排序列表项。如何更改代码,使其仅显示1公里范围内的位置,而不仅仅是重新排序整个列表。

代码语言:javascript
复制
    <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>
EN

回答 1

Stack Overflow用户

发布于 2012-06-13 18:55:22

你可以这样写:

代码语言:javascript
复制
function filterList(){
   $('ol li').each(function(){
      if($(this).data('distance') > 1){
        $(this).remove();
      }
   });
}

代替上面的解决方案,你可以做下面的事情?

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11013233

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档