Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of lon\lat points, start with nearest

I have location from GPS (lon_base, lat_base). I have a list of locations (lon1, lat1|lon2, lat2|lon3, lat3...) This list is very long and is around the world.

My questions are: 1. How do I get from that list only the lon\lat that are 1 mile from my lon_base\lat_base? 2. How do I sort them from closest to farthest?

Thanks in advance!

like image 962
OkyDokyman Avatar asked Mar 22 '11 18:03

OkyDokyman


2 Answers

public static List<Location> sortLocations(List<Location> locations, final double myLatitude,final double myLongitude) {
    Comparator comp = new Comparator<Location>() {
        @Override
        public int compare(Location o, Location o2) {
            float[] result1 = new float[3];
            android.location.Location.distanceBetween(myLatitude, myLongitude, o.Lat, o.Long, result1);
            Float distance1 = result1[0];

            float[] result2 = new float[3];
            android.location.Location.distanceBetween(myLatitude, myLongitude, o2.Lat, o2.Long, result2);
            Float distance2 = result2[0];

            return distance1.compareTo(distance2);
        }
    };


    Collections.sort(locations, comp);
    return locations;
}

Where the List of Locations is a list containing your own Location class, not the android.location.Location.

like image 118
aaronsw Avatar answered Oct 22 '22 05:10

aaronsw


You want to define your own Comparator that, in general, looks something like this:

LonLat myHouse = /* whatever */ ;
Comparable comp = new Comparable () {
    LonLat a;
    int compareTo (Object b) {
        int aDist = calcDistance(a, myHouse) ;
        int bDist = calcDistance(b, myHouse) ;
        return aDist - bDist;
    }
};
myLonLatList.sort(lonLatList, comp);

where calcDistance() simply calculates the distance between the two points. If you're on Android, I think Google Maps has a function somewhere in their API that will do this for you.

EDIT : You'll want your calcDistance() function to look like ChrisJ's distance function.

-tjw

like image 32
Travis Webb Avatar answered Oct 22 '22 05:10

Travis Webb