Alessandro
Alessandro

Reputation: 4110

Changing pin color MKMapView

I add annotations to my map in this way:

MyAnnotation *annotationPoint2 = [[MyAnnotation alloc] init];
annotationPoint2.coordinate = anyLocation;
annotationPoint2.title = [NSString stringWithFormat:@"%@", obj];
annotationPoint2.subtitle = @"";  //or set to nil
annotationPoint2.keyValue = [NSString stringWithFormat:@"%@", key];
[mapPins addAnnotation:annotationPoint2];

The pins are all red, and I would like them all green. How can I change the color? I have tried the following, but it still gives a red mark:

annotationPoint2.pinColor = MKPinAnnotationColorGreen;

Upvotes: 11

Views: 20047

Answers (3)

casillas
casillas

Reputation: 16813

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation 
  {
    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"pin"];
    annView.pinColor = MKPinAnnotationColorGreen;
    return annView;
  }

Upvotes: 23

developermike
developermike

Reputation: 625

Swift3 is in this way:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin")

    if annotation.title! == "My Place" {

        annotationView.pinTintColor = UIColor.green

    } else {

        annotationView.pinTintColor = UIColor.red
    }


    return annotationView
}

Upvotes: 5

user467105
user467105

Reputation:

The pinColor property is defined in the MKPinAnnotationView class (not the MKAnnotation protocol).

You create a MKPinAnnotationView in the viewForAnnotation delegate method. If you haven't implemented that delegate, you get standard red pins by default.

In that delegate method, you create an instance of MKPinAnnotationView and you can set its pinColor to green.

Upvotes: 6

Related Questions