My app includes an MKMapView
that shows the users location as a blue bullet.
Now I made a button (just like in a normal map app) that when pressed should center the map view onto the users location, but I don't know how to do so.
You could just set map view user tracking mode to MKUserTrackingModeFollow. It would automatically set map center on user location.
- (IBAction)centerMapOnUserButtonClicked:(id)sender {
[self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
}
[self.mapView setCenterCoordinate:self.mapView.userLocation.coordinate animated:YES];
I've just been working on this problem today.
It's possible to add a MKUserTrackingBarButtonItem button to a toolbar to copy the functionality from the iOS Maps app. When pushing the button it will turn tracking on and off.
- (void)viewDidLoad
{
[super viewDidLoad];
MKUserTrackingBarButtonItem *buttonItem = [[MKUserTrackingBarButtonItem alloc] initWithMapView:self.map];
self.navigationItem.rightBarButtonItem = buttonItem;
}
A fuller answer is available here.
Swift 3 Solution
@IBAction func centerUserButton(_ sender: Any) {
self.mapView.setCenter(self.mapView.userLocation.coordinate, animated: true)
}
This is it :
locationManager = [[CLLocationManager alloc] init];
if ([CLLocationManager locationServicesEnabled])
{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];;
MKCoordinateRegion region;
region.center=coordinate;
MKCoordinateSpan span;
span.latitudeDelta=10.015; // Vary as you need the View for
span.longitudeDelta=10.015;
region.span=span;
[mapView setRegion:region];
self.mapView.showsUserLocation = YES;