To calculate the distance between two latitudes and longitudes in Java, you can use the following methods (both code examples return in meters):
1. Haversine formula (medium precision, recommended general scenarios)
public class GeoDistanceCalculator { public static double haversineDistance(double lat1, double lon1, double lat2, double lon2) { final int EARTH_RADIUS_METERS = 6371000; double dLat = (lat2 - lat1); double dLon = (lon2 - lon1); double a = (dLat / 2) * (dLat / 2) + ((lat1)) * ((lat2)) * (dLon / 2) * (dLon / 2); double c = 2 * Math.atan2((a), (1 - a)); return EARTH_RADIUS_METERS * c; } public static void main(String[] args) { double distance = haversineDistance(40.7128, -74.0060, 34.0522, -118.2437); ("distance:" + distance + " rice"); // Output is about 3933476 meters } }
2. Spherical cosine theorem (simple but low precision)
public static double sphericalCosineLaw(double lat1, double lon1, double lat2, double lon2) { final int EARTH_RADIUS_METERS = 6371000; double lat1Rad = (lat1); double lat2Rad = (lat2); double dLon = (lon2 - lon1); double distance = ( (lat1Rad) * (lat2Rad) + (lat1Rad) * (lat2Rad) * (dLon) ) * EARTH_RADIUS_METERS; return distance; }
3. Vincenty formula (high precision, suitable for complex models)
public static double vincentyDistance(double lat1, double lon1, double lat2, double lon2) { final double a = 6378137.0; // Equatorial radius (meters) final double b = 6356752.314245; // Pole radius (meters) final double f = 1 / 298.257223563; // Flat double L = (lon2 - lon1); double U1 = ((1 - f) * ((lat1))); double U2 = ((1 - f) * ((lat2))); double sinU1 = (U1), cosU1 = (U1); double sinU2 = (U2), cosU2 = (U2); double lambda = L, lambdaPrev; double sinSigma, cosSigma, sigma, sinAlpha, cosSqAlpha, C; int maxIterations = 200; do { double sinLambda = (lambda), cosLambda = (lambda); sinSigma = ( (cosU2 * sinLambda) * (cosU2 * sinLambda) + (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) ); if (sinSigma == 0) return 0; // overlapping points cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda; sigma = Math.atan2(sinSigma, cosSigma); sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma; cosSqAlpha = 1 - sinAlpha * sinAlpha; C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha)); lambdaPrev = lambda; lambda = L + (1 - C) * f * sinAlpha * (sigma + C * sinSigma * (cosSigma + C * cosSigma * (-1 + 2 * C * cosSigma * cosSigma))); } while ((lambda - lambdaPrev) > 1e-12 && --maxIterations > 0); double uSq = cosSqAlpha * (a * a - b * b) / (b * b); double A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))); double B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))); double deltaSigma = B * sinSigma * (cosSigma + B / 4 * (cosSigma * (-1 + 2 * B * cosSigma * cosSigma) - B / 6 * cosSigma * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cosSigma * cosSigma))); return b * A * (sigma - deltaSigma); }
4. Android built-in method (Android development only)
import ; public static float androidLocationDistance(double lat1, double lon1, double lat2, double lon2) { Location location1 = new Location("point1"); (lat1); (lon1); Location location2 = new Location("point2"); (lat2); (lon2); return (location2); // Return to the meters}
5. Polar coordinate system approximation method (fast but low precision)
public static double polarApproximation(double lat1, double lon1, double lat2, double lon2) { final int EARTH_RADIUS_METERS = 6371000; double dLat = (lat2 - lat1); double dLon = (lon2 - lon1); double avgLat = ((lat1 + lat2) / 2); double x = dLon * (avgLat); double y = dLat; return (x * x + y * y) * EARTH_RADIUS_METERS; }
6. Method comparison
method | Accuracy | speed | Applicable scenarios |
---|---|---|---|
Haversine formula | Medium (~0.5%) | quick | General scenarios (navigation, LBS service) |
Vincenty formula | Height (~0.5mm) | slow | High precision requirements (surveying and mapping, scientific research) |
Spherical cosine theorem | Low | quick | Quick estimation (non-critical scenarios) |
Android Location | medium | medium | Android application development |
Polar approximation method | Low | Extremely fast | Quickly filter a large number of coordinate points |
7. Choose a suggestion
Recommended Haversine formula: It works for most applications (such as calculating distances between two cities).
Choose Vincenty formula when high precision is required: for example, geological survey or navigation system.
Direct use of Android development (): no need to implement algorithms manually.
Use polar approximation to quickly filter coordinate points: for example, filter nearby locations in the database.
8. Knowledge extension
Python method to calculate the distance between two points in latitude and longitude
There are many ways to calculate the distance between two latitudes and longitudes in Python, commonly used include the Haversine formula and the Vincenty formula. Below are examples of implementation of these two methods.
1. Haversine formula
The Haversine formula is a simple and commonly used method to calculate the shortest distance (large circle distance) between two points on the earth's surface.
import math def haversine_distance(lat1, lon1, lat2, lon2): # Earth's radius, unit: km R = 6371.0 # Convert latitude and longitude to radians lat1_rad = (lat1) lon1_rad = (lon1) lat2_rad = (lat2) lon2_rad = (lon2) # Calculate the difference dlat = lat2_rad - lat1_rad dlon = lon2_rad - lon1_rad # Haversine formula a = (dlat / 2)**2 + (lat1_rad) * (lat2_rad) * (dlon / 2)**2 c = 2 * math.atan2((a), (1 - a)) distance = R * c return distance # Example usagelat1, lon1 = 34.052235, -118.243683 # Los Angeles' latitude and longitudelat2, lon2 = 40.712776, -74.005974 # Latitude and longitude of New York distance = haversine_distance(lat1, lon1, lat2, lon2) print(f"Distance using Haversine formula: {distance} km")
2. Vincenty formula
Vincenty formulas provide higher accuracy and are suitable for situations where precise measurements are required.
The first one uses the geographiclib library
pip install geographiclib from import Geodesic def vincenty_distance(lat1, lon1, lat2, lon2): geod = Geodesic.WGS84 # Use WGS84 ellipsoid model result = (lat1, lon1, lat2, lon2) distance = result['s12'] / 1000.0 # Distance unit: km return distance # Example usagelat1, lon1 = 34.052235, -118.243683 # Los Angeles' latitude and longitudelat2, lon2 = 40.712776, -74.005974 # Latitude and longitude of New York distance = vincenty_distance(lat1, lon1, lat2, lon2) print(f"Distance using Vincenty formula: {distance} km")
The second type uses geopy library
pip install geopy from import geodesic def calculate_distance_with_geopy(lat1, lon1, lat2, lon2): # Define two points point1 = (lat1, lon1) point2 = (lat2, lon2) # Calculate the distance between two points distance = geodesic(point1, point2).kilometers return distance # Example usagelat1, lon1 = 34.052235, -118.243683 # Los Angeles' latitude and longitudelat2, lon2 = 40.712776, -74.005974 # Latitude and longitude of New York distance = calculate_distance_with_geopy(lat1, lon1, lat2, lon2) print(f"Distance using Vincenty formula: {distance} km")
Haversine formula: easy to use, suitable for most situations.
Vincenty formula: Higher precision, suitable for situations where accurate measurement is required.
This is the article about Java's example code for calculating latitude and longitude distance. For more related content on calculating latitude and longitude distance, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!