[objective-c]加载到 MKMapVIew 只有五个批注

发布时间: 2017/3/27 3:05:10
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有 MKMapView,,我想知道我如何能找到最近 5 注释给用户,并只在 MKMapView 上显示它们。

目前是我的代码︰

- (void)loadFiveAnnotations {
    NSString *string = [[NSString alloc] initWithContentsOfURL:url];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSArray *chunks = [string componentsSeparatedByString:@";"];
    NSArray *keys = [NSArray arrayWithObjects:@"type", @"name", @"street", @"address1", @"address2", @"town", @"county", @"postcode", @"number", @"coffeeclub", @"latlong", nil];   
    // max should be a multiple of 12 (number of elements in keys array)
    NSUInteger max = [chunks count] - ([chunks count] % [keys count]);
    NSUInteger i = 0;

    while (i < max)
    {
        NSArray *subarray = [chunks subarrayWithRange:NSMakeRange(i, [keys count])];
        NSDictionary *dict = [[NSDictionary alloc] initWithObjects:subarray forKeys:keys];
        // do something with dict
        NSArray *latlong = [[dict objectForKey:@"latlong"] componentsSeparatedByString:@","];
        NSString *latitude = [[latlong objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSString *longitude = [[latlong objectAtIndex:1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        CLLocationDegrees lat = [latitude floatValue];
        CLLocationDegrees longi = [longitude floatValue];
        Annotation *annotation = [[Annotation alloc] initWithCoordinate:CLLocationCoordinate2DMake(lat, longi)];
        annotation.title = [dict objectForKey:@"name"];
        annotation.subtitle = [NSString stringWithFormat:@"%@, %@, %@",[dict objectForKey:@"street"],[dict objectForKey:@"county"], [dict objectForKey:@"postcode"]];
        [mapView addAnnotation:annotation];
        [dict release];

        i += [keys count];
    }
}

解决方法 1:

一个长的答案,已经大部分是写斯蒂芬 Poletto 过帐时和包含的示例代码如何使用一些内置的方法进行排序数组,所以我仍然值得张贴虽然基本答案是相同 (即"为自己挑选最接近五,只有那些转嫁")︰

你要排序您批注是按距离为自己,并提交仅最近五至 MKMapView。如果你有两个 CLLocations,那么你可以得到它们之间的距离使用distanceFromLocation:方法 (这是 getDistanceFrom︰ 之前 iOS 3.2; 这个名称现在被否决)。

因此,例如,假设您批注类有方法 ' setReferenceLocation: 对,你通过 CLLocation 和 getter 'distanceFromReferenceLocation',返回这两个之间的距离,你可以做︰

// create and populate an array containing all potential annotations
NSMutableArray *allPotentialAnnotations = [NSMutableArray array];

for(all potential annotations)
{
    Annotation *annotation = [[Annotation alloc]
                                            initWithCoordinate:...whatever...];
    [allPotentialAnnotations addObject:annotation];
    [annotation release];
}

// set the user's current location as the reference location
[allPotentialAnnotations
      makeObjectsPerformSelector:@selector(setReferenceLocation:) 
      withObject:mapView.userLocation.location];

// sort the array based on distance from the reference location, by
// utilising the getter for 'distanceFromReferenceLocation' defined
// on each annotation (note that the factory method on NSSortDescriptor
// was introduced in iOS 4.0; use an explicit alloc, init, autorelease
// if you're aiming earlier)
NSSortDescriptor *sortDescriptor = 
              [NSSortDescriptor
                  sortDescriptorWithKey:@"distanceFromReferenceLocation" 
                  ascending:YES];

[allPotentialAnnotations sortUsingDescriptors:
                          [NSArray arrayWithObject:sortDescriptor]];

// remove extra annotations if there are more than five
if([allPotentialAnnotations count] > 5)
{
    [allPotentialAnnotations
               removeObjectsInRange:NSMakeRange(5, 
                           [allPotentialAnnotations count] - 5)];
}

// and, finally, pass on to the MKMapView
[mapView addAnnotations:allPotentialAnnotations];

根据在哪里你从加载,你犯了需要创建批注本地存储 (在内存中或磁盘上),然后选择最近五,每当用户移动。或者注册自己的 CLLocationManager 委托或键-值观察地图视图的 userLocation 属性。如果你有很多潜在的注释然后排序所有的他们是有点浪费,你将更好地告知,使用四叉树或 kd 树。

官方微信
官方QQ群
31647020