//此距离方法引用自
https://stackoverflow.com/a/16794680/6138660
public static double distance(double lat1, double lat2, double lon1,
double lon2) {
final int R = 6371; // Radius of the earth
double latDistance = Math.toRadians(lat2 - lat1);
double lonDistance = Math.toRadians(lon2 - lon1);
double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // convert to meters
distance = Math.pow(distance, 2);
return Math.sqrt(distance);
}
private List<Unit> nearestUnits(List<Unit> lists, Unit x, int limit) {
lists.sort(new Comparator<Unit>() {
@Override
public int compare(Unit o1, Unit o2) {
double flagLat = x.getLat();
double flagLon = x.getLon();
double o1DistanceFromFlag = distance(flagLat, o1.getLat(), flagLon, o1.getLon());
double o2DistanceFromFlag = distance(flagLat, o2.getLat(), flagLon, o2.getLon());
return Double.compare(o1DistanceFromFlag, o2DistanceFromFlag);
}
});
return lists.subList(0, limit);;
}