- (MKAnnotationView *) mapView не вызывается - PullRequest
0 голосов
/ 02 марта 2011

В моем коде метод - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation не вызывается. Я не знаю почему. Может кто-нибудь помочь мне?

Ниже мой код:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation 
{

    MKPinAnnotationView *pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@","];
    NSLog(@"pin map");
    if(pinView == nil) 
    {
        pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@""];

        pinView.animatesDrop = YES;
        pinView.canShowCallout = YES;

        UIImage *image = [UIImage imageNamed:@"ann.png"];

        CGRect resizeRect;

        resizeRect.size = image.size;
        CGSize maxSize = CGRectInset(self.view.bounds,
                                     [map annotationPadding],
                                     [map annotationPadding]).size;*/
        maxSize.height -= self.navigationController.navigationBar.frame.size.height + [map calloutHeight];
        if (resizeRect.size.width > maxSize.width)
            resizeRect.size = CGSizeMake(maxSize.width, resizeRect.size.height / resizeRect.size.width * maxSize.width);
        if (resizeRect.size.height > maxSize.height)
            resizeRect.size = CGSizeMake(resizeRect.size.width / resizeRect.size.height * maxSize.height, maxSize.height);

        resizeRect.origin = (CGPoint){0.0f, 0.0f};

        UIGraphicsBeginImageContext(resizeRect.size);
        [image drawInRect:resizeRect];
        UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        pinView.image = resizedImage;
        pinView.opaque = NO;

        UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        [rightButton addTarget:self
                        action:@selector(showDetails:)
              forControlEvents:UIControlEventTouchUpInside];
        pinView.rightCalloutAccessoryView = rightButton;

        if (annotation == mapView.userLocation)
        {

            return nil;
        }
        return pinView;

    } 
    else 
    {

        pinView.annotation = annotation;
    }

    return pinView;

}

Вот как я добавляю аннотации на карту:

-(void) Annotations:(int)i
{

    /*NSString* address = [mpartyDetail objectAtIndex:i];
    address = [[address componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: @""];
    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv", address];
    NSLog(@"nsstring %@",urlString);
    NSString *locationString = [[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:urlString]] autorelease];
    NSLog(@"location string %@",locationString);
    NSArray *latlng = [locationString componentsSeparatedByString:@","];
    NSLog(@"the latlng %@",latlng);

    float lat = [[latlng objectAtIndex:2] floatValue];
    float lng = [[latlng objectAtIndex:3] floatValue]; */
    NSLog(@"ann");
    lat = [[latiArray objectAtIndex:i]floatValue];
    lng = [[longiArray objectAtIndex:i]floatValue]; 
    CLLocationCoordinate2D newCoord = {lat,lng};
    mapAnnotations* annotation = [[mapAnnotations alloc] initWithCoordinate:newCoord];

    [mapView addAnnotation:annotation];

}

mapAnnotations - это другой класс. Приведенный ниже код показывает метод этого класса, который вызывается:

- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate{

    NSLog(@"the cor");
    self = [super init];

    if (self != nil) {
        NSLog(@"in");
        _coordinate = coordinate;

    }

    return self;

}

Идея состоит в том, что я добавляю аннотации, когда пользователь нажимает на карту, и пользователь может дать любой заголовок этому пину. Мне нужна выноска, чтобы показать название, введенное пользователем. Аннотации добавляются. Но я не могу получить выноску, так как этот метод не вызывается.

Ответы [ 3 ]

2 голосов
/ 02 марта 2011

Вы назначили класс, содержащий этот метод, в качестве делегата для представления вашей карты, добавили ли вы какие-либо аннотации к представлению карты, и являются ли места для этих аннотаций, фактически видимыми в той части карты, которая в данный момент отображается на экране?

1 голос
/ 22 марта 2011

, как кто-то справедливо указал, делегат не был установлен в тот же класс в моем случае все, что я сделал, было в коде, где я добавил аннотацию, я написал код:

mapView.delegate=self;

и это прекрасно сработало для меня. если вы этого не сделали, это может сработать и для вас, дроид.

0 голосов
/ 02 марта 2011

Как вы добавляете аннотации на карту? Я использую следующее

while(some condition){
MapAnnotation *annotation = [[MapAnnotation alloc] initWithLatitude:(float)goLat Longitude:(float)goLng title:(NSString*)recallTask.blurb subtitle:(NSString*)recallTask.location];
        [appDelegate.annArray addObject:annotation];
        [annotation release];
        annotation = nil;
    }
[self.mapView addAnnotations:appDelegate.annArray];
...