1

I would like to know how do I check whether a given point is within certain km radius of another fixed point?

Ophitect
  • 543
  • 4
  • 18

3 Answers3

4

Location class has methods to calculate distance between points

First option (with distanceTo method):

// firstLocation and secondLocation are Location class instances
float distance = firstLocation.distanceTo(secondLocation); // distance in meters

if (distance < 5000) {
    // distance between first and second location is less than 5km
}

Second option (with static distanceBetween method):

// distance is stored in result array at index 0
float[] result = new float[1];
Location.distanceBetween (startLat, startLng, endLat, endLng, result);

if (result[0] < 5000) {
    // distance between first and second location is less than 5km
}
mata
  • 361
  • 3
  • 14
0

you can try this below function:

public static double getDistanceFromLatLngInKm(LatLng c1, LatLng c2) {
      int R = 6371; // Radius of the earth in km

      double lat1 = c1.latitude;
      double lat2 = c2.latitude;

      double lon1 = c1.longitude;
      double lon2 = c2.longitude;

      double dLat = deg2rad(lat2-lat1); 
      double dLon = deg2rad(lon2-lon1);

      double a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
        Math.sin(dLon/2) * Math.sin(dLon/2)
        ; 

      double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
      double d = R * c; // Distance in km
      return d;
}

public static double deg2rad(double deg) {
      return deg * (Math.PI/180);
}

Hope it will help you..

Rushabh Patel
  • 3,052
  • 4
  • 26
  • 58
0

Try this :-

public static Double methodName(double nLat, double nLon,
            double nLat2, double nLon2) {
            double nD;

            Location locA = new Location("point A");
            locA.setLatitude(nLat);
            locA.setLongitude(nLon);

            Location locB = new Location("point B");
            locB.setLatitude(nLat2);
            locB.setLongitude(nLon2);

            nD = locA.distanceTo(locB);

            return nD;


            }
Rohit
  • 810
  • 2
  • 9
  • 34