Get locations within radius

点点圈 提交于 2019-12-21 05:33:07

问题


In a database I have stored around 500 records, each with a latitude and a longitude.

In an Activity I implement a LocationListener and in the onLocationChanged-method I need to show the records that is within a radius of XX metres from the location received from this listener.

Is there an (easy) way to do this, either in SQL or Java?


回答1:


Try this sample code,

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 */ 
                }


来源:https://stackoverflow.com/questions/18462993/get-locations-within-radius

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!