Idan Moshe Idan Moshe - 6 months ago 84
iOS Question

How to sort array of objects(latitude, longitude) by nearest distance?

I've an array from core data and I'm trying to think how can I sort the array by the nearest distance:

for (int i=0; i<allTasks.count; i++) {
id singleTask = allTasks[i];
double latitude = [singleTask[@"latitude"] doubleValue];
double longitude = [singleTask[@"longitude"] doubleValue];

The distance between current location and all the locations in the array.
I know how to calculate the distance, I don't know how to sort them.

  1. get the CLLocation for your currentPosition (this is done via CLLocationManager)

  2. calculate the distances for each item and store distance+item as a Pair in a Dictionary

  3. Sort Dictionary allKeys array with compare: selector


CLLocation *current = ...;
NSMutableDictionary *distsAndTasks [NSMutableDictionary dictionary];

for(id task in allTasks) {
    CLLocation *taskLoc = [[CLLocation alloc] longitude:task.long];//!
    CLLocationDistance dist = [taskLoc distanceFrom:current];
    if(distsAndTasks[@(dist)]) {
        NSMutableArray *equidstants = [distsAndTasks[@(dist)] mutableCopy];
        [equidstants addObject:task]; 
        distsAndTasks[@(dist)] = equidstants; 
    else {
        distsAndTasks[@(dist)] = @[task]; 

NSArray *sortedDists = [distsAndTasks.allKeys sortedArrayUsingSelector:@selector(compare:)];

//the tasks can now be access in a sorted way
for(NSNumber *dist in sortedDists) {
    NSArray *tasksAtDistance = distsAndTasks[dist];
    NSLog(@"%@", tasksAtDistance);