我正在开发一个服务器端使用 Java 的 Android 应用程序。当我收到用户的坐标时,我正在检索餐馆列表,我正在计算与用户的距离,并以升序对它们进行排序。
现在,一切正常。唯一的问题是计算的距离具有非常高的灵敏度。我正在寻找的是,以这种方式显示的距离,即 1.2km、200m、12.2km 等,它正在适当地计算和附加公里或米。我怎样才能做到这一点?
目前的输出是:
Restaurant distance is 6026.203669933703
Restaurant distance is 1.0248447083638768
Restaurant distance is 1.0248447083638768
Restaurant distance is 1.0248447083638768
计算和排序代码:
@Override
public List<Restaurant> getNearbyRestaurants(double longitude, double latitude) {
final int R = 6371; // Radius of the earth
List<Restaurant> restaurantList = this.listRestaurants();
List<Restaurant> nearbyRestaurantList = new ArrayList<>();
for(Restaurant restaurant : restaurantList){
Double latDistance = toRad(latitude-restaurant.getLatitude());
Double lonDistance = toRad(longitude-restaurant.getLongitude());
Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) +
Math.cos(toRad(latitude)) * Math.cos(toRad(restaurant.getLatitude())) *
Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
Double distance = R * c;
restaurant.setDistanceFromUser(distance);
if(distance < 10){
nearbyRestaurantList.add(restaurant);
}
}
if(!(nearbyRestaurantList.isEmpty())) {
Collections.sort(nearbyRestaurantList, new Comparator<Restaurant>() {
@Override
public int compare(Restaurant o1, Restaurant o2) {
if (o1.getDistanceFromUser() > o2.getDistanceFromUser()) {
return 1;
}
if (o1.getDistanceFromUser() < o2.getDistanceFromUser()) {
return -1;
}
return 0;
}
});
for(Restaurant restaurant : restaurantList){
System.out.println("Restaurant distance is "+restaurant.getDistanceFromUser());
}
return nearbyRestaurantList;
}
return null;
}
请让我知道我错过了什么。非常感谢。:-)