I am working on a Android application for which the server-side is in Java. When I receive co-ordinates from the user, I am retrieving a list of restaurants, I am calculating the distance from the user, and sorting them in ascending fashion.
Right now, everything works. The only problem is that the distance computed has a very high-sensitivity. What I am looking for is, distance shown in this manner i.e 1.2km, 200m, 12.2km, etc , which is calculating and appending Km or Meters appropriately. How can I achieve this?
Output currently is :
Restaurant distance is 6026.203669933703
Restaurant distance is 1.0248447083638768
Restaurant distance is 1.0248447083638768
Restaurant distance is 1.0248447083638768
Code for calculation & sorting :
@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;
}
Kindly let me know what am I missing. Thanks a lot. :-)
If the distance is below 1000m then depending on the application use either the exact value of the integral meters, or round to the next 10 meters:
473.343 -> 470m or 473 depending on the goal of your application
If the distance is above 1km but below 100km use one digit after decimal point:
1.5km, 10.3km, 99.5km
If above 100km round to integral kilometers: 101km, 9453km