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