我正在开发一个Android应用程序,该应用程序的服务器端使用Java。当我收到用户的坐标时,我会检索一份餐厅列表,计算与用户的距离,并按升序排序。
现在,一切正常。唯一的问题是计算出的距离具有非常高的灵敏度。我想要的是,以这种方式显示的距离,即1.2公里、200米、12.2公里等,这是适当地计算和添加公里或米。我怎样才能做到这一点?
当前输出为:
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;
}
请告诉我我缺了什么。非常感谢。:-)
如果距离低于1000m,则根据应用,使用整米的精确值,或四舍五入到下一个10米:
473.343->470m或473,具体取决于应用程序的目标
如果距离在1公里以上但在100公里以下,则使用小数点后一位数字:
1.5公里、10.3公里、99.5公里
如果超过100km,则取整千米:101km,9453km