Search code examples
iphonemapkitmkannotationmkannotationview

Change Pin Color when user tapped


I would change the color from red to green of an annotation when the user pin tapped addition to changing its title and subtitle.

I am truly lost. I searched how to make a custom annotation pin, ok. I found the implementation of the method when the user touches the pin didSelectAnnotationView and it works when I tap the annotation NSLog(@"Tap") ; , but now I can not change the pin that was touched.

Thank you very much everyone for your contributions.

Ciao


Solution

  • To set the pin color, make use of MKPinAnnotationView pinColor property.

    MKPinAnnotationView *pin = [[MKPinAnnotationView alloc] init]
    pin.pinColor = MKPinAnnotationColorGreen;
    

    For custom annotation image, set the image property, as such.

    UIImage *annImage = [UIImage imageNamed:@"AnnotationIcon.png"];
    annView.image = annImage;
    

    Do note that the MKPinAnnotationView animateDrop property will not work on custom images. There's a way to duplicate that animation though. See How do I animate MKAnnotationView drop?

    Update So bascially, you do this if you wanna change from red to green upon being selected.

    - (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKPinAnnotationView *)view {
        view.pinColor = MKPinAnnotationColorGreen;
    
    }
    
    - (MKAnnotationView *)mapView:(MKMapView *)aMapView
                viewForAnnotation:(id)ann {
    
        NSString *identifier = @"myPin";
        MKPinAnnotationView *annView = (MKPinAnnotationView *)
        [aMapView dequeueReusableAnnotationViewWithIdentifier:identifier];
        if (annView == nil) {
            annView= [[[MKPinAnnotationView alloc] initWithAnnotation:ann
                                                   reuseIdentifier:identifier]
                   autorelease];
        } else {
            annView.annotation = ann;
        }
    // you can define the properties here.
    
    return annView;
    }