Changing pin color MKMapView
Asked Answered
M

3

11

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;
Micrometry answered 12/10, 2012 at 12:58 Comment(0)
E
23
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation 
  {
    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"pin"];
    annView.pinColor = MKPinAnnotationColorGreen;
    return annView;
  }
Ecotone answered 12/10, 2012 at 14:47 Comment(4)
this code works, but even the current user location becomes green, even if I want it blue with the circles round it. How can I do that?Micrometry
if([[annotation title] isEqualToString:@"Current Location"]) { annView.pinColor = MKPinAnnotationColorGreen; }else{annView.pinColor = MKPinAnnotationColorRed;}Ecotone
@Micrometry You need to return nil when annotation == mapView.userLocation to show the blue dot for user location and the circle around itSides
Remember to set the view's canShowCallout if you want the title/subtitle information to be displayed when the pin is touchedAyeaye
E
6

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.

Engrossing answered 12/10, 2012 at 13:14 Comment(0)
M
5

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
}
Malley answered 12/10, 2016 at 17:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.