0

I have an application in which i have a location cordinates.(ie lattitude and longitude).Then i have a list of friends with their (lat&longs).

I need to sort my friends array according to the condition that who is nearest to me comes first

.I have their and mine lats and longs.Can anybody help me to achieve this?

1

2 Answers 2

2
CLLocation *myLoc = [[CLLocation alloc] initWithLatitude:42.5000 longitude:1.5000];
NSArray *arr = [NSArray arrayWithObjects:
                [[CLLocation alloc] initWithLatitude:42.5000 longitude:1.5000],
                [[CLLocation alloc] initWithLatitude:24.0000 longitude:54.0000],
                [[CLLocation alloc] initWithLatitude:33.0000 longitude:65.0000],
                [[CLLocation alloc] initWithLatitude:17.0500 longitude:-61.8000],
                [[CLLocation alloc] initWithLatitude:18.2500 longitude:-63.1667],
                [[CLLocation alloc] initWithLatitude:41.0000 longitude:20.0000],
                [[CLLocation alloc] initWithLatitude:40.0000 longitude:45.0000],
                nil
                ];

CLLocation *nearestLoc = nil;
CLLocationDistance nearestDis = DBL_MAX;
for (CLLocation *loc in arr) {
    CLLocationDistance distance = [myLoc distanceFromLocation:loc];
    if (nearestDis > distance) {
        nearestLoc = loc;
        nearestDis = distance;
    }
}
0

Hmm, it depends how you are storing this information. If you are storing it in say postgres with postgis then I'm pretty sure you can sort by distance. If not you could snag a distance calculation algorithm and just run it for all your friends, possibly cache it, and then sort by the distance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.