Pergunta

Ei pessoal! Estou tendo alguns problemas em dar a um mkannotationview uma imagem em vez de uma exibição de pino. Em outras palavras, estou tendo problemas para exibir uma imagem de destino (Target.png) em vez da visualização normal do PIN. Aqui está o meu código ---


// .h file
#import  //Here it says to import mapkit & UIKit.  The code blockquote doesn't let me
#import  //show you that

@interface AddressAnnotation : NSObject {
    CLLocationCoordinate2D coordinate;

    NSString *mTitle;
    NSString *mSubTitle;
}

@end

@interface ChosenLocationMap : UIViewController {
IBOutlet MKMapView *mapView;
AddressAnnotation *addAnnotation;
}
-(CLLocationCoordinate2D) addressLocation;

// .m file
@implementation AddressAnnotation
@synthesize coordinate;

- (NSString *)subtitle{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString *stitle = [prefs objectForKey:@"addressKey"];
    return @"%@",stitle;
}

- (NSString *)title{
    return @"TARGET";
}

-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
    coordinate=c;
    NSLog(@"%f,%f",c.latitude,c.longitude);
    return self;
}

@end


@implementation ChosenLocationMap
@synthesize destinationLabel, startbutton, accelloop, aimview, bombblowupview, bombleftview1, bombleftview2, bombleftview3, firebutton;

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
- (void)viewDidLoad {
mapView.mapType = MKMapTypeSatellite;
MKCoordinateSpan span;
    span.latitudeDelta=0.2;
    span.longitudeDelta=0.2;
CLLocationCoordinate2D location = [self addressLocation];
region.span=span;
    region.center=location;
if(addAnnotation != nil) {
        [mapView removeAnnotation:addAnnotation];
        [addAnnotation release];
        addAnnotation = nil;
    }
addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
    [mapView addAnnotation:addAnnotation];
 [super viewDidLoad];
}
-(CLLocationCoordinate2D) addressLocation {
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString *destinationstring = [prefs objectForKey:@"addressKey"];
    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv", 
                           [destinationstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
    NSArray *listItems = [locationString componentsSeparatedByString:@","];

    double latitude = 0.0;
    double longitude = 0.0;

    if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) {
        latitude = [[listItems objectAtIndex:2] doubleValue];
        longitude = [[listItems objectAtIndex:3] doubleValue];
    }
    else {
        //Show error
    }
    CLLocationCoordinate2D location;
    location.latitude = latitude;
    location.longitude = longitude;

    return location;
}

- (MKAnnotationView *)map:(MKMapView *)map viewForAnnotation:(id )annotation{
    MKAnnotationView *annView;
    annView = (MKAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier:annotation.title];

    if(annView == nil)
        annView = [[[MKAnnotationView alloc]
                    initWithAnnotation:annotation reuseIdentifier:annotation.title] autorelease];
    else
        annView.annotation = annotation;


    [annView setImage:[UIImage imageNamed:@"target.png"]];
    annView.canShowCallout = TRUE;

    return annView;
}

Observe que eu incluí apenas o código que realmente envolve o MapView. Desde já, obrigado!

EDIT: Eu mudei o código no meu documento xcode para as alterações na resposta 1. Estou com preguiça de transferir tudo para o bloco de código acima e, ainda assim, a imagem ainda não funciona.

Shoop da Edit: Obrigado por responder! Minha solução foi que eu esqueci de dizer mapView.delegate = self. Tchau!

Foi útil?

Solução

Uau, muito errado com este código :-)

Primeiro você está perdendo um @property declaração em seu AddressAnnotation

@property (nonatomic,assign) CLLocationCoordinate2D coordinate;

No método de legenda, você faz isso:

return @"%@",stitle;

Mas este é o Objective-C e não o Python, então você pode querer mudar isso para:

return stitle;

Então sua initWithithininate está completamente errada. Você não inicializa super. Isto é melhor:

-(id) initWithCoordinate: (CLLocationCoordinate2D) c
{
    if ((self = [super init]) != nil) {
        coordinate=c;
        NSLog(@"%f,%f",c.latitude,c.longitude);
    }
    return self;
}

Tente consertar essas coisas primeiro para ver se isso ajuda :-)

Outras dicas

Eu sou novo no objetivo C, mas acho que o protótipo da sua função de delegado deve ser:

- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id )annotation{
    MKAnnotationView *annView;

O nome delegado é visão do mapa: ViewForAnnotation:, não mapa: ViewForAnnotation:

Além disso, o endereço não implementa o protocolo Mkannotation

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top