Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MKPointAnnotation won't change colors

I need to change the color for an MKPointAnnotation object, but the method I wrote seems to only generate red pins. The method works fine, but when I call the function, passing the parameter of one of the given constant, all pins that appear on the map are red (the default). Any thoughts? Code below.

    -(MKAnnotationView*) returnPointView: (CLLocationCoordinate2D) location andTitle: (NSString*) title andColor: (int) color{
        /*Method that acts as a point-generating machine. Takes the parameters of the location, the title, and the color of the 
         pin, and it returns a view that holds the pin with those specified details*/

        MKPointAnnotation *resultPin = [[MKPointAnnotation alloc] init];
        MKPinAnnotationView *result = [[MKPinAnnotationView alloc] initWithAnnotation:resultPin reuseIdentifier:Nil];
        [resultPin setCoordinate:location];
        resultPin.title = title;
        result.pinColor = color;
        return result;
        }

//Function that calls above method
    for(Party *party in allParties){
            if(!party.alreadyAdded){
                CLLocationCoordinate2D location = [party getPartylocation];
                NSString *partyTitle = [party getPartyName];
                MKAnnotationView *partyPin = [self returnPointView:location andTitle:partyTitle andColor:MKPinAnnotationColorGreen];
                [self.map addAnnotation:partyPin.annotation];
                NSLog(@"Adding Successful!");
                party.alreadyAdded = YES;
            }

        }
like image 353
Jake Byman Avatar asked Mar 22 '23 05:03

Jake Byman


1 Answers

You have to conform to the MKMapViewDelegate protocol in the header of your ViewController.

@interface mapViewController : UIViewController <MKMapViewDelegate>
@end

Then, in the implementation you have to write the method :

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

That is called each time an annotation is drawn. It's here that you should call your method, not only when adding the annotation.

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

    MKAnnotationView *pinView = [self returnPointView:annotation.coordinate andTitle:annotation.title andColor:MKPinAnnotationColorGreen];

    return pinView;
}

Finally, set the ViewController as its UIMapView delegate delegate in viewDidLoad :

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.mapView setDelegate:self];
}

I suggest you have a look at the MapCallouts example project in Xcode, it's clear and simple.

Just as well, you should use dequeueReusableAnnotationViewWithIdentifier in order to be more memory efficient (as does the example).

like image 186
vinaut Avatar answered Apr 01 '23 19:04

vinaut