优化后的目的地顺序:
目的地1: 113.0787409570716, 28.17748698056088
目的地3: 112.9994095942885, 28.16504090914147
目的地2: 113.0544746932484, 28.18304377689985
import java.util.HashMap;
import java.util.Map;
public class 坐标最短距离 {
public static void main(String[] args) {
String startingPoint = "112.979, 28.326228";
Map<String, String> destinations = new HashMap<>();
destinations.put("目的地1", "113.0787409570716, 28.17748698056088");
destinations.put("目的地2", "113.0544746932484, 28.18304377689985");
destinations.put("目的地3", "112.9994095942885, 28.16504090914147");
Map<String, String> optimizedOrder = optimizeDestinationOrder(startingPoint, destinations);
System.out.println("优化后的目的地顺序:");
for (Map.Entry<String, String> entry : optimizedOrder.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
private static Map<String, String> optimizeDestinationOrder(String startingPoint, Map<String, String> destinations) {
Map<String, String> optimizedOrder = new HashMap<>();
String currentLocation = startingPoint;
while (!destinations.isEmpty()) {
double minDistance = Double.MAX_VALUE;
String nearestDestinationName = null;
String nearestDestination = null;
for (Map.Entry<String, String> entry : destinations.entrySet()) {
String name = entry.getKey();
String destination = entry.getValue();
double distance = calculateDistance(currentLocation, destination);
if (distance < minDistance) {
minDistance = distance;
nearestDestinationName = name;
nearestDestination = destination;
}
}
if (nearestDestinationName != null) {
optimizedOrder.put(nearestDestinationName, nearestDestination);
destinations.remove(nearestDestinationName);
currentLocation = nearestDestination;
}
}
return optimizedOrder;
}
private static double calculateDistance(String coordinate1, String coordinate2) {
double lat1 = Double.parseDouble(coordinate1.split(", ")[1]);
double lon1 = Double.parseDouble(coordinate1.split(", ")[0]);
double lat2 = Double.parseDouble(coordinate2.split(", ")[1]);
double lon2 = Double.parseDouble(coordinate2.split(", ")[0]);
double earthRadius = 6371.0;
double lat1Rad = Math.toRadians(lat1);
double lon1Rad = Math.toRadians(lon1);
double lat2Rad = Math.toRadians(lat2);
double lon2Rad = Math.toRadians(lon2);
double dlon = lon2Rad - lon1Rad;
double dlat = lat2Rad - lat1Rad;
double a = Math.sin(dlat / 2) * Math.sin(dlat / 2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(dlon / 2) * Math.sin(dlon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = earthRadius * c;
return distance;
}
}