【问题标题】:Get locations within radius获取半径内的位置
【发布时间】:2013-08-30 01:21:12
【问题描述】:

在一个数据库中,我存储了大约 500 条记录,每条记录都有一个纬度和一个经度。

在一个 Activity 中,我实现了一个 LocationListener,在 onLocationChanged 方法中,我需要显示距离从该侦听器接收到的位置 XX 米半径范围内的记录。

是否有一种(简单的)方法可以做到这一点,无论是在 SQL 还是 Java 中?

【问题讨论】:

标签: android sql location


【解决方案1】:

试试这个示例代码,

rs = st.executeQuery("SELECT longititude,latitude FROM  location");
                while (rs.next()) {
                double venueLat =rs.getDouble("latitude");
                double venueLng = rs.getDouble("longititude");

                double latDistance = Math.toRadians(userLat - venueLat);
                double lngDistance = Math.toRadians(userLng - venueLng);
                double a = (Math.sin(latDistance / 2) * Math.sin(latDistance / 2)) +
                                (Math.cos(Math.toRadians(userLat))) *
                                (Math.cos(Math.toRadians(venueLat))) *
                                (Math.sin(lngDistance / 2)) *
                                (Math.sin(lngDistance / 2));

                double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

                double dist = 6371 * c;             
                if (dist<50){
                    /* Include your code here to display your records */ 
                }

【讨论】:

  • 你能用简单的英语解释一下这段代码的作用吗? UserLat 和 UserLng 是当前位置,对吧? dist
  • userLat 和 userLng 是用户当前位置,venueLat 和venueLng 是数据库中的位置。 dist 是这两个位置之间的距离,以 KM 为单位。 6371 是地球的半径(平均半径 = 6,371 公里)
  • 我可以参考或解释您使用的方程式吗?在此先感谢...
  • @Coderji 我知道我来得太晚了,但上面使用的等式是Haversine formula
  • 小问题,但您可能可以先计算 Math.sin(latDistance / 2),然后在计算 a 时使用它,这样可以节省您的程序在每个循环中执行 4 次,然后 Math.sin。 cos(Math.toRadians(userLat)) 可以在while循环之前,不需要对每条记录都这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多