luodangjia
2024-12-10 ee7ce5d1cbf80bee0a15c1e5bc5eaa30858d812b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.hollywood.applet.utils;
 
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
 
public class DistanceCalculator1 {
 
    private static final double EARTH_RADIUS_KM = 6378.138; // Updated Earth's radius to match SQL query
 
    /**
     * Calculates the distance between two sets of coordinates (latitude and longitude) in kilometers,
     * rounded to two decimal places. Input coordinates are expected to be provided as Strings.
     *
     * @param lat1Str Latitude of the first point as a String in degrees
     * @param lon1Str Longitude of the first point as a String in degrees
     * @param lat2Str Latitude of the second point as a String in degrees
     * @param lon2Str Longitude of the second point as a String in degrees
     * @return The distance between the two points in kilometers, rounded to two decimal places
     * @throws NumberFormatException If any input coordinate cannot be parsed as a double
     */
    public static double calculateDistanceBetweenCoordinates(String lat1Str, String lon1Str, String lat2Str, String lon2Str) throws NumberFormatException {
        double lat1 = Double.parseDouble(lat1Str);
        double lon1 = Double.parseDouble(lon1Str);
        double lat2 = Double.parseDouble(lat2Str);
        double lon2 = Double.parseDouble(lon2Str);
 
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
 
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
 
        double a = Math.pow(Math.sin(dLat / 2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dLon / 2), 2);
        double c = 2 * Math.asin(Math.sqrt(a));
 
        double distance = EARTH_RADIUS_KM * c;
        DecimalFormat df = new DecimalFormat("0.##", DecimalFormatSymbols.getInstance(Locale.US));
        return Double.parseDouble(df.format(distance));
    }
}