Reputation:
I have an array of custom object. And the object have parameters including latitude and longitude. I want to sort that array with respect to distance of them from the current location. I can able to get the distance between the current location and each object. But I dont know how to sort it after calculating the distance. For Eg:
MainArray = [{name:NYC, lat:1.11, lng:2.22}, {name:CAL, lat:3.33, lng:4.44}, {name:LA, lat:5.55, lng:6.66}].
So lets say am in centre of three places and then I want to sort them in the nearby order. Sorry if the above syntax is wrong, as I cant post the original data because it is too big.
How can I achieve this? Please help.
Upvotes: 0
Views: 208
Reputation: 861
Almost the same as previous answer but without adding field:
CLLocation *yourLocation = [[CLLocation alloc] initWithLatitude:.... longitude:...];
NSArray *array = @[@{ @"name": @"NYC", @"lat": @1.11, @"lng": @2.22}, @{@"name":@"CAL", @"lat":@3.33, @"lng":@4.44}, @{@"name":@"LA", @"lat":@5.55, @"lng":@6.66}];
array = [array sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:[obj1[@"lat"] double] longitude:[obj1[@"lng"] double]];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:[obj2[@"lat"] double] longitude:[obj2[@"lng"] double]];
CLLocationDistance distance1 = [location1 distanceFromLocation:yourLocation];
CLLocationDistance distance2 = [location2 distanceFromLocation:yourLocation];
if (distance1 > distance2) {
return (NSComparisonResult)NSOrderedDescending;
}
if (distance1 < obj2 distance2) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
Upvotes: 2
Reputation: 2824
You can add another field in your object named distanceFromLocation.
Then just before you need to display the distances, update the distanceFromLocation in the array of your objects using below code.
CLLocation *arrayCoord = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];
CLLocation *yourLocation = [[CLLocation alloc] initWithLatitude:yourLocationLat longitude:yourLocationLong];
CLLocationDistance distance = [arrayCoord distanceFromLocation:yourLocation];
After that sort your array of objects using sort descriptors
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distanceFromLocation"
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [arrayOfYourObjects sortedArrayUsingDescriptors:sortDescriptors];
Upvotes: 0