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