Reputation: 6893
I was trying to utilise map kit to show my current location using MKMapView and its delegate method, didUpdateUserLocation
but when I zoom in and comes really close, I would see multiple pins. Then after some suggestions I realised, every time, the location is updated the pin is re-created. So, I took my add annotation code out of the delegate method.
Here is my code-
#import "MapViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface MapViewController ()<MKMapViewDelegate, CLLocationManagerDelegate, UITextFieldDelegate> {
MKPointAnnotation *myAnnotation;
}
@property (nonatomic, strong) IBOutlet MKMapView *mapView;
@property (nonatomic, strong) IBOutlet UITextField *searchTextField;
@property (strong, nonatomic) CLLocationManager *locationManager;
@end
@implementation MapViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.mapView.delegate=self;
self.mapView.showsUserLocation=YES;
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
myAnnotation = [[MKPointAnnotation alloc]init];
myAnnotation.coordinate = self.mapView.userLocation.coordinate;
myAnnotation.title = @"Current Location";
[self.mapView addAnnotation:myAnnotation];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark-
#pragma mark- MapView Delegate
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}
@end
but now there is no pin.
Upvotes: 2
Views: 978
Reputation: 501
=> MKMapView automatically places an annotation of class MKUserLocation when you set mapView.showsUserLocation = YES:
You can replace the default view for this annotation to whatever default annotation view you want by doing this in mapView:viewForAnnotation:
- (MKAnnotationView *) mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation {
if ([annotation isKindOfClass:[MKUserLocation class]]) {
// replace the following with code to generate and return custom user position annotation view
return customAnnotationView;
}
//*** other code ***//
}
Upvotes: 3
Reputation: 501
yes right if you do not want to display pin in mapview then keep out side of code or remove it whitch you have written in didUpdateUserLocation.
Upvotes: 0
Reputation: 927
Dear you need to put your myAnnotation code outside your delegate method "didUpdateUserLocation"
Note : you need to make Annotation in viewDidLoad then use didUpdateUserLocation for update your coordinate
Upvotes: 2