iPhone: Sorting based on location

前端 未结 5 1707
天命终不由人
天命终不由人 2020-12-14 13:37

I have been working on an iPhone app, where-in i have list of users in a NSMutableArray like below.

myMutableArray: (
    {
        FirstName = Getsy;
               


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 14:12

    - (void)viewDidLoad {
        [super viewDidLoad];
    // This Array Taken Globally
    List_of_locationsArray =[[NSMutableArray alloc]initWithObjects:
      @{@"latitude" : @"17.415045",@"logitude":@"78.421424"} ,@{@"latitude" : @"17.415045",@"logitude":@"78.421424"},@{@"latitude" : @"17.415045",@"logitude":@"78.421424"},@{@"latitude" : @"17.415045",@"logitude":@"78.421424"},@{@"latitude" : @"17.415045",@"logitude":@"78.421424"}
     ,nil];
    
    }
    
    -(void)sortingLocationsArray{
    //    CLLocation* currentLocation =[[CLLocation alloc]initWithLatitude:[currentLatitude doubleValue] longitude:[currentLogitude doubleValue]];
          CLLocation* currentLocation =[[CLLocation alloc]initWithLatitude: currentLatitudeHere longitude:CurrentLogHere];
    
       NSMutableArray* tempLocationsArr = [[NSMutableArray alloc]initWithCapacity:[locationsArray count]];
        for (int i=0; i<[locationsArray count]; i++) {
            CLLocationDegrees latValue = [[locationsArray[i] objectForKey:@"latitude"] doubleValue];
            CLLocationDegrees longValue = [[locationsArray[i] objectForKey:@"logitude"] doubleValue];
            CLLocation* location = [[CLLocation alloc]initWithLatitude:latValue longitude:longValue];
            [tempLocationsArr addObject:location];
    
            NSArray* sortLocationArry = [tempLocationsArr sortedArrayUsingComparator:^NSComparisonResult(CLLocation* location1, CLLocation* location2) {
                CLLocationDistance distA = [location1 distanceFromLocation:currentLocation];
                CLLocationDistance distB = [location2 distanceFromLocation:currentLocation];
                if (distA < distB) {
                    return NSOrderedAscending;
                } else if ( distA > distB) {
                    return NSOrderedDescending;
                } else {
                    return NSOrderedSame;
                }
            }];
    
          //ArrayAfterSorting is another mutable Array to Store Sorting Data
            [ArrayAfterSorting removeAllObjects];
            [sortLocationArry enumerateObjectsUsingBlock:^(CLLocation* location, NSUInteger idx, BOOL *stop) {
                NSMutableDictionary *tempDict = [[NSMutableDictionary alloc]init];
                [tempDict setObject:[NSString stringWithFormat:@"%f",location.coordinate.latitude] forKey:@"latitude"];
                [tempDict setObject:[NSString stringWithFormat:@"%f",location.coordinate.longitude] forKey:@"logitude"];
                [ArrayAfterSorting addObject:tempDict];
    
    
            }];
         NSLog(@"sortedArray : %@", ArrayAfterSorting);
        }
    
    }
    

提交回复
热议问题