我已阅读并按照How do I zoom an MKMapView to the users current location without CLLocationManager?
上的说明操作然而,虽然我确实得到了当前的用户位置,但我无法让地图在视觉上居中。
例如,在viewDidLoad函数中,如何使地图围绕用户已知位置进行可视化居中?我已粘贴下面的CurrentLocation代码(请参阅viewDidLoad中的XXX注释
#import "MapViewController.h"
#import "PlacemarkViewController.h"
@implementation MapViewController
@synthesize mapView, reverseGeocoder, getAddressButton;
- (void)viewDidLoad
{
[super viewDidLoad];
// XXX HERE: How can I cause self.mapView to actually recenter itself at self.mapview.userLocation.location?
mapView.showsUserLocation = YES;
}
- (void)viewDidUnload
{
self.mapView = nil;
self.getAddressButton = nil;
}
- (void)dealloc
{
[reverseGeocoder release];
[mapView release];
[getAddressButton release];
[super dealloc];
}
- (IBAction)reverseGeocodeCurrentLocation
{
self.reverseGeocoder =
[[[MKReverseGeocoder alloc] initWithCoordinate:mapView.userLocation.location.coordinate] autorelease];
reverseGeocoder.delegate = self;
[reverseGeocoder start];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
NSString *errorMessage = [error localizedDescription];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Cannot obtain address."
message:errorMessage
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
PlacemarkViewController *placemarkViewController =
[[PlacemarkViewController alloc] initWithNibName:@"PlacemarkViewController" bundle:nil];
placemarkViewController.placemark = placemark;
[self presentModalViewController:placemarkViewController animated:YES];
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
// we have received our current location, so enable the "Get Current Address" button
[getAddressButton setEnabled:YES];
}
@end
答案 0 :(得分:26)
看起来您可以简单地使用MKMapView class的centerCoordinate
属性 - 文档说:
更改此属性中的值会使地图在新坐标上居中,而不会更改当前缩放级别。它还会更新
region
属性中的值,以反映新的中心坐标和维持当前缩放级别所需的新跨度值。
基本上,你只是这样做:
self.mapView.centerCoordinate = self.mapView.userLocation.location.coordinate;