I'm having trouble displaying MKAnnotationViews on a map in MapKit. I use iOS 7 and now I look at forums and the Internet many times, trying different samples and settings.
Below I have the easiest setup (I think) for it to work. The application contains one ViewController with a toolbar with a button at the top, and the rest is a MapView. The button starts the zoomToUser: (UIBarButtonItem *) method of the sender. Right-clicking and checking my points and delegates seem correct. I have NSLog instructions that run to display some debugging information.
First VC:
#import "ViewController.h"
#import "Data.h"
@interface ViewController () <MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
- (IBAction)zoomToUser:(UIBarButtonItem *)sender;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.mapView.showsUserLocation = YES;
Data *ann = [[Data alloc] init];
[self.mapView addAnnotation:ann];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self zoomToUser:nil];
}
-(IBAction)zoomToUser:(UIBarButtonItem *)sender
{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(self.mapView.userLocation.coordinate, 2000, 2000);
NSLog(@"region: %f x %f",self.mapView.userLocation.coordinate.latitude,self.mapView.userLocation.coordinate.longitude);
[self.mapView setRegion:region animated:YES ];
NSArray *arr = self.mapView.annotations;
for(int i = 0, max = arr.count; i < max; i++)
{
id<MKAnnotation> annotation = arr[i];
NSLog(@"%d of %d: %@ (%@)",i+1,max,annotation.title, [annotation class]);
}
}
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation
{
NSString *reuseId = @"Test";
if([annotation isKindOfClass:[MKUserLocation class]])
{
return nil;
}
else if( [annotation isKindOfClass:[Data class]])
{
MKAnnotationView *annov = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
if(!annov)
{
annov = [[MKAnnotationView alloc]initWithAnnotation:annotation
reuseIdentifier:reuseId];
}
else
{
annov.annotation = annotation;
}
annov.canShowCallout = YES;
NSLog(@"Title: %@",annotation.title);
return annov;
}
else
{
return nil;
}
}
@end
And the class Data:
#import "Data.h"
@implementation Data
-(NSString *)title
{
return @"The title";
}
-(NSString *)subtitle
{
return @"A subtitle";
}
-(CLLocationCoordinate2D)coordinate
{
CLLocationCoordinate2D coordinate;
coordinate.latitude = 60.123456;
coordinate.longitude = 10.123456;
return coordinate;
}
@end
Data.h:
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface Data : NSObject <MKAnnotation>
@end
And ViewController.h:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface ViewController : UIViewController
@end
, viewForAnnotation , , , , .
BarButton zoomToUser: - , , MKUserLocation , .
MapView , , , , ?