【问题标题】:Get 5 Nearest Annotations MKMapKit获取 5 个最近的注释 MKMapKit
【发布时间】:2011-03-07 22:43:32
【问题描述】:

我正在使用 MKMapKit 来获取 100 公里半径内的最近位置。但是我想知道如何对数组进行排序,以便在数组顶部给我最近的五个注释。

我当前的代码是:

    CLLocation *currentlocation = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
    annotation.distanceToTarget = [currentlocation distanceFromLocation:usrlocation];
    annotation.title = [dict objectForKey:@"name"];
    annotation.subtitle = [NSString stringWithFormat:@"%@, %@, %@",[dict objectForKey:@"street"],[dict objectForKey:@"county"], [dict objectForKey:@"postcode"]];
    annotation.subtitle = [annotation.subtitle stringByReplacingOccurrencesOfString:@", ," withString:@""];
    if (annotation.distanceToTarget/1000 < 168) {
        abc++;
        NSLog(@"Distances Lower Than 168: %i", abc);
        [storesLessThan100KAway addObject:annotation];
        NSLog(@"Stores Count: %i", [storesLessThan100KAway count]);
    }
    for (int i = 0; i <= 5; i++) {
        //NSLog(@"Stores Count For Loop: %i", [storesLessThan100KAway count]);
        if ([storesLessThan100KAway count] > 5) {
            [mapView addAnnotation:[storesLessThan100KAway objectAtIndex:i]];
        }
    }   

【问题讨论】:

    标签: iphone objective-c xcode ios4 sorting


    【解决方案1】:

    为注释编写自己的比较方法:

    - (NSComparisonResult)compare:(Annotation *)otherAnnotation {
        if (self.distanceToTarget > otherAnnotation.distanceToTarget) {
            return NSOrderedDescending;
        } else if (self.distanceToTarget < otherAnnotation.distanceToTarget) {
            return NSOrderedAscending;
        } else {
            return NSOrderedSame;
        }
    }
    

    然后您可以使用选择器进行排序:

    NSArray *sortedArray = [storesLessThan100KAway sortedArrayUsingSelector:@selector(compare:)];
    

    【讨论】:

      【解决方案2】:

      如果您使用的是 iOS4,您可以使用块来简化此操作:

      NSComparator compareAnnotations = ^(Annotation *obj1, Annotation *obj2) {
          if (obj1.distanceToTarget > obj2.distanceToTarget) {
              return NSOrderedDescending;
          } else if (obj1.distanceToTarget < obj2.distanceToTarget) {
              return NSOrderedAscending;
          } else {
              return NSOrderedSame;
          }
      };
      
      NSArray *sortedArray = [storesLessThan100KAway sortedArrayUsingComparator:compareAnnotations];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-22
        • 2015-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-27
        • 1970-01-01
        • 2012-02-08
        相关资源
        最近更新 更多