LatLng:检查LatLng的给定点是否在另一个点的5km半径范围内

时间:2014-08-13 08:54:02

标签: java android google-maps

我想知道如何检查给定点是否在另一个固定点的某个公里范围内?

3 个答案:

答案 0 :(得分:3)

Location类有计算点之间距离的方法

第一个选项(使用distanceTo方法):

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

第二个选项(使用静态distanceBetween方法):

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

答案 1 :(得分:0)

您可以尝试以下功能:

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);
}

希望它会帮助你..

答案 2 :(得分:0)

试试这个: -

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;


            }