我正在使用服务器端使用Java的Android应用程序。当我从用户那里收到坐标时,我正在检索餐馆列表,正在计算与用户的距离,并以升序对它们进行排序。

现在,一切正常。唯一的问题是计算出的距离具有很高的灵敏度。我正在寻找的是以这种方式显示的距离,即1.2km,200m,12.2km等,它正在适当地计算并附加Km或Meters。我该如何实现?

当前输出为:

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.5km,10.3km,99.5公里

如果超过100公里,则变为整数公里:
101公里,9453公里

10-07 19:05
查看更多