3

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?

perene
  • 421
  • 2
  • 6
  • 16

1 Answers1

4

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 */ 
                }
ponraj
  • 738
  • 1
  • 7
  • 21
  • Could you in plain english explain a bit about what this code does? UserLat and UserLng is the current position, right? dist<50, is that in metres? What's the constant 6371? – perene Aug 28 '13 at 07:33
  • userLat and userLng is the users current position, venueLat and venueLng is the location from database. dist is the distance between these two positions in KM. 6371 is earth’s radius (mean radius = 6,371km) – ponraj Aug 28 '13 at 09:17
  • can I have a reference or explanation to the equation you used? thanks in advance... – Coderji Jan 08 '14 at 08:16
  • @Coderji I know I'm way too late but the equation used above is [Haversine formula](http://www.movable-type.co.uk/scripts/latlong.html). – Zerocchi May 12 '16 at 15:39
  • Minor quibble, but you could probably calculate Math.sin(latDistance / 2) first and then use it in calculating a, and that would save your program working it out 4 times per cycle, and Math.cos(Math.toRadians(userLat)) could be before the while loop, no need to do that for each record. – Andy Moignard Oct 31 '19 at 14:45