How to determine whether the longitude and latitude of two regions are within a certain range (super easy to use)

To determine whether the longitude and latitude of two areas are within a certain range, you can use the distance calculation formula to calculate the distance between two locations and compare it with the given range. Here is a sample code that uses Haversine's formula in spherical trigonometry to calculate the distance between two locations:

public class LocationUtils {
    
    
    private static final double EARTH_RADIUS = 6371; // 地球半径(单位:公里)

    public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
    
    
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);

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

        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        double distance = EARTH_RADIUS * c;
        return distance;
    }

    public static boolean isWithinRange(double lat1, double lon1, double lat2, double lon2, double range) {
    
    
        double distance = calculateDistance(lat1, lon1, lat2, lon2);
        return distance <= range;
    }
}

In the above code, calculateDistance()the method is used to calculate the distance between two latitude and longitude, and the unit is returned in kilometers. isWithinRange()The method is used to determine whether the distance between two locations is within a given range, where rangethe parameter represents the radius of the range, in kilometers.

Usage example:

double lat1 = 40.7128; // 纬度1
double lon1 = -74.0060; // 经度1
double lat2 = 37.7749; // 纬度2
double lon2 = -122.4194; // 经度2
double range = 100; // 范围(单位:公里)

boolean isWithinRange = LocationUtils.isWithinRange(lat1, lon1, lat2, lon2, range);
if (isWithinRange) {
    
    
    System.out.println("两个地点在范围内");
} else {
    
    
    System.out.println("两个地点不在范围内");
}

Please note that the above code is a simplified calculation based on spherical trigonometry, and actual geographical distances may be affected by the shape of the earth. If more precise distance calculations are required, consider using more complex algorithms or a geographic information system (GIS) library to handle them.

Guess you like

Origin blog.csdn.net/qq_44543774/article/details/133272099