I'm using MapKit to display the user's location relative to pins around them. I'd like to be able to mimic the functionality that Maps provides via the crosshair button in the lower left-hand corner of the screen. I'm already aware that MapKit provides a CLLocation object with the user's location via MKUserLocation, I just wanted to seek advice on how I should keep focus on that location. My initial inclination was to use an NSTimer to center the map on that coordinate every 500ms or so.
Is there a better way to do this? Is there something built in to MapKit that I'm missing that will accomplish this?
Thanks so much, Brendan
If you're on IOS5+ this is VERY easy. Just change the "userTrackingMode" using code such as:
[_mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
This will smoothly follow the users current location. If you drag the map it will even set the tracking mode back to MKUserTrackingModeNone
which is usually the behaviour you want.
It's really simple to have the map update the user location automatically just like the google maps. Simply set showsUserLocation to YES
self.mapView.showsUserLocation = YES
...and then implement the MKMapViewDelegate to re-center the map when the location is updated.
-(void) mapView:(MKMapView *)mapView
didUpdateUserLocation:(MKUserLocation *)userLocation
{
if( isTracking )
{
pendingRegionChange = YES;
[self.mapView setCenterCoordinate: userLocation.location.coordinate
animated: YES];
}
}
And to allow the user to zoom & pan without stealing the view back to the current location...
-(void) mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
if( isTracking && ! pendingRegionChange )
{
isTracking = NO;
[trackingButton setImage: [UIImage imageNamed: @"Location.png"]
forState: UIControlStateNormal];
}
pendingRegionChange = NO;
}
-(IBAction) trackingPressed
{
pendingRegionChange = YES;
isTracking = YES;
[mapView setCenterCoordinate: mapView.userLocation.coordinate
animated: YES];
[trackingButton setImage: [UIImage imageNamed: @"Location-Tracking.png"]
forState: UIControlStateNormal];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With