I am currently struggling to use a custom map pin image instead of the default coloured pins. I have tried some guides online but can’t seem to integrate it into my current set up.
Currently I have a certain coloured (tinted) pin set during certain times (online) and when the time is outside these parameters the pin turns a different colour.
I want to change these pins to two different custom pin images that I have created; one for online and one for offline.
I have read something about the MKPinAnnotationView not liking the pinView.image property (I have tried this and can confirm it doesn’t work).
If someone could edit this code so I can have a “online.png“ image for the annotation tag 0 and an “offline.png” image for the annotation tag 1, that would be perfect.
MapViewController.m
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
MKPinAnnotationView *pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomPinAnnotationView"];
UIButton *advertButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
pinView.rightCalloutAccessoryView = advertButton;
pinView.canShowCallout = YES;
pinView.draggable = NO;
pinView.highlighted = YES;
if (annotation == mapView.userLocation)
return nil;
if (([(Annotation*)annotation tag] == 0) && [[(Annotation*)annotation area] isEqualToString:@"Online"])
{
pinView.pinTintColor = [UIColor colorWithRed:0.92 green:0.21 blue:0.21 alpha:1];
pinView.alpha = 1;
[advertButton addTarget:self action:@selector(Online:) forControlEvents:UIControlEventTouchUpInside];
}
else if (([(Annotation*)annotation tag] == 1) && [[(Annotation*)annotation area] isEqualToString:@"Offline"])
{
pinView.pinTintColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.5];
pinView.alpha = 1;
[advertButton addTarget:self action:@selector(Offline:) forControlEvents:UIControlEventTouchUpInside];
}
return pinView;
}
Any help would be greatly appreciated; I am not a coder by nature so go easy.
Cheers
Lewis
If you want to display a pin as annotation, you use MKPinAnnotationView
. If you want to use a custom annotation image, you had to use MKAnnotationView
, and set the image
property.
So I suggest to replace
MKPinAnnotationView *pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomPinAnnotationView"];
by
MKAnnotationView *pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomPinAnnotationView"];
and set the image
property, e.g. using:
pinView.image = [UIImage imageNamed:@„xxx“];
Of course, you should rename pinView
, CustomPinAnnotationView
and xxx
appropriately.