17

Right now I am populating a map view with annotations, and also displaying the user's current location. With the viewForAnnotation method, it overrides all annotations with the default red pin, but I want to return the views for the other annotations, but keep the user location the default blue beacon. Is there a way to do this simply or do I have to create a new annotation view and return the right one depending on the annotation?

Right now I have something like:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    if (annotation.coordinate == locationManager.location.coordinate) {

return nil;

    }else {

    MKAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"Beacon"];

    // Button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    button.frame = CGRectMake(0, 0, 23, 23);
    annotationView.rightCalloutAccessoryView = button;


    annotationView.canShowCallout = YES;

    return annotationView;
}
}

But I can't equate the two because I can't get the coordinate property out of the annotation argument.

Anybody know any solutions to this?

Hudson Buddy
  • 726
  • 2
  • 9
  • 20

2 Answers2

30

Check out the documentation here:

http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKMapViewDelegate_Protocol/MKMapViewDelegate/MKMapViewDelegate.html

As it states:

If the object in the annotation parameter is an instance of the MKUserLocation class, you can provide a custom view to denote the user’s location. To display the user’s location using the default system view, return nil.

You can check for it like so:

if([annotation isKindOfClass: [MKUserLocation class]]) {
  return nil;
}

Swift:

guard annotation as? MKUserLocation == nil else { return nil }
calimarkus
  • 9,955
  • 2
  • 28
  • 48
0

Swift 5.0

Put a check at the top of the function to ignore the userLocation:

   func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        guard annotation as? MKUserLocation != mapView.userLocation else { return }
HalR
  • 11,411
  • 5
  • 48
  • 80