2013-04-09 5 views
1

У меня около 500 аннотаций на моем MKMapView, и я сгруппировал их с OCMapView, которые заменяют обычный MKMapView. Во всяком случае, моя аннотация кластеризована, но не очень хорошо, поэтому мне нужна небольшая помощь. Я вижу кластерные аннотации, и они очень хорошо дополняют друг друга. Если я приближаюсь к ним, они становятся нечеткими. Пока все хорошо, но все отдельные аннотации называются Cluster, а их счет равен нулю. Может быть, это лишь незначительная/логическая проблема. Некоторое понимание здесь какой-то код для вас:Кластеризованные аннотации перезаписывают неклассифицированные аннотации

#pragma mark - map delegate 
- (MKAnnotationView *)mapView:(MKMapView *)aMapView viewForAnnotation:(id <MKAnnotation>)annotation 
{ 
    MKAnnotationView *annotationView; 

    // if it's a cluster 
    if ([annotation isKindOfClass:[OCAnnotation class]]) 
    { 

     OCAnnotation *clusterAnnotation = (OCAnnotation *)annotation; 

     annotationView = (MKAnnotationView *)[aMapView dequeueReusableAnnotationViewWithIdentifier:@"ClusterView"]; 
     if (!annotationView) 
     { 
      annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"ClusterView"]; 
      annotationView.canShowCallout = YES; 
      annotationView.centerOffset = CGPointMake(0, -20); 
     } 
     //calculate cluster region 
     CLLocationDistance clusterRadius = mapView.region.span.longitudeDelta * mapView.clusterSize * 111000/2.0f; //static circle size of cluster 

     MKCircle *circle = [MKCircle circleWithCenterCoordinate:clusterAnnotation.coordinate radius:clusterRadius * cos([annotation coordinate].latitude * M_PI/180.0)]; 
     [circle setTitle:@"background"]; 
     [mapView addOverlay:circle]; 

     MKCircle *circleLine = [MKCircle circleWithCenterCoordinate:clusterAnnotation.coordinate radius:clusterRadius * cos([annotation coordinate].latitude * M_PI/180.0)]; 
     [circleLine setTitle:@"line"]; 
     [mapView addOverlay:circleLine]; 
     NSLog(@"%@", annotationArray); 

     // set title 
     clusterAnnotation.title = @"Cluster"; 
     clusterAnnotation.subtitle = [NSString stringWithFormat:@"Containing annotations: %d", [clusterAnnotation.annotationsInCluster count]]; 

     // set its image 
     annotationView.image = [UIImage imageNamed:@"Pin.png"]; 

     // change pin image for group 
     if (mapView.clusterByGroupTag) 
     { 
      if ([clusterAnnotation.groupTag isEqualToString:kTYPE1]) 
      { 
       annotationView.image = [UIImage imageNamed:@"bananas.png"]; //OC examples for debug 
      } 
      else if([clusterAnnotation.groupTag isEqualToString:kTYPE2]) 
      { 
       annotationView.image = [UIImage imageNamed:@"oranges.png"]; //OC examples for debug 
      } 
      clusterAnnotation.title = clusterAnnotation.groupTag; 
     } 
    } 
    // If it's a single annotation 
    else if([annotation isKindOfClass:[OCMapViewHelpAnnotation class]]) 
    { 
     OCMapViewHelpAnnotation *singleAnnotation = (OCMapViewHelpAnnotation *)annotation; 
     annotationView = (MKAnnotationView *)[aMapView dequeueReusableAnnotationViewWithIdentifier:@"singleAnnotationView"]; 
     if (!annotationView) 
     { 
      annotationView = [[MKAnnotationView alloc] initWithAnnotation:singleAnnotation reuseIdentifier:@"singleAnnotationView"]; 
      annotationView.canShowCallout = YES; 
      annotationView.centerOffset = CGPointMake(0, -20); 
     } 
     singleAnnotation.title = singleAnnotation.groupTag; 

     if ([singleAnnotation.groupTag isEqualToString:kTYPE1]) 
     { 
      annotationView.image = [UIImage imageNamed:@"banana.png"]; 
     } 
     else if([singleAnnotation.groupTag isEqualToString:kTYPE2]) 
     { 
      annotationView.image = [UIImage imageNamed:@"orange.png"]; 
     } 
    } 
    // Error 
    else 
    { 
     annotationView = (MKPinAnnotationView *)[aMapView dequeueReusableAnnotationViewWithIdentifier:@"errorAnnotationView"]; 
     if (!annotationView) 
     { 
      annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"errorAnnotationView"]; 
      annotationView.canShowCallout = NO; 
      ((MKPinAnnotationView *)annotationView).pinColor = MKPinAnnotationColorRed; 
     } 
    } 

    return annotationView; 
} 

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay 
{ 
    MKCircle *circle = overlay; 
    MKCircleView *circleView = [[MKCircleView alloc] initWithCircle:overlay]; 

    if ([circle.title isEqualToString:@"background"]) 
    { 
     circleView.fillColor = [UIColor yellowColor]; 
     circleView.alpha = 0.25; 
    } 
    else if ([circle.title isEqualToString:@"helper"]) 
    { 
     circleView.fillColor = [UIColor redColor]; 
     circleView.alpha = 0.25; 
    } 
    else 
    { 
     circleView.strokeColor = [UIColor blackColor]; 
     circleView.lineWidth = 0.5; 
    } 

    return circleView; 
} 

- (void)mapView:(MKMapView *)aMapView regionDidChangeAnimated:(BOOL)animated 
{ 
    [mapView removeOverlays:mapView.overlays]; 
    [mapView doClustering]; 
} 

Я заметил, что if([annotation isKindOfClass:[OCMapViewHelpAnnotation class]]) никогда не называют, но это должно, если есть некоторые аннотации вне кластера.

Благодарим Вас за внимание

EDIT

Annotation

Обычно он наполнен Informations, как «Имя» и «Улица», но после того, как черчения это перезапись все с «Кластер» и "содержащие аннотации: 0"

EDIT 2

- (void)loadKml:(NSURL *)url 
{ 
    // parse the kml 

    Parser *parser = [[Parser alloc] initWithContentsOfURL:url]; 
    parser.rowElementName = @"Placemark"; 
    parser.elementNames = @[@"name", @"Snippet", @"coordinates", @"description"]; 
    //parser.attributeNames = @[@"src"]; 
    [parser parse]; 

    // add annotations for each of the entries 
    annotationArray = [[NSMutableArray alloc] init]; 

    for (NSDictionary *locationDetails in parser.items) 
    { 
     OCAnnotation *annotation = [[OCAnnotation alloc] init]; 
     annotation.title = locationDetails[@"name"]; 
     annotation.subtitle = locationDetails[@"Snippet"]; 
     NSArray *coordinates = [locationDetails[@"coordinates"] componentsSeparatedByString:@","]; 
     annotation.coordinate = CLLocationCoordinate2DMake([coordinates[1] floatValue], [coordinates[0] floatValue]); 
     annotation.groupTag = annotation.title; 
     [annotationArray addObject:annotation]; 
//  NSLog(@"%@", annotation.title); 
    } 
    [self.mapView addAnnotations:annotationArray]; 
} 

ответ

2

Я разработчик OCMapView. Не могли бы вы объяснить, как воспроизвести вашу проблему?
Это звучит очень необычно, так как вы разместили пример кода ...


Update:
Исправлена ​​ошибка скрывается в методе loadKml:, где вы создаете OCAnnotation.
OCAnnotation зарезервировано OCMapView для кластеров. Вы не должны использовать OCAnnotation или любой подкласс в качестве собственных аннотаций.

+0

Я просто добавил картинку, чтобы отобразить ее лучше. я попытался сохранить код простым и реализовать свои собственные аннотации для кодирования. – CTSchmidt

+0

Хорошо, я понимаю, в чем проблема, но не как воспроизвести ее. Было бы интересно увидеть больше кода, особенно, как добавить аннотации. – yinkou

+0

Я использую kml-файл, в котором хранятся мои местоположения с кучей информации. – CTSchmidt

Смежные вопросы