6

我已阅读并遵循有关如何在没有 CLLocationManager 的情况下将 MKMapView 缩放到用户当前位置的说明?

但是,虽然我确实获得了当前用户位置,但我实际上无法使地图在视觉上居中。

例如,在 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
4

1 回答 1

26

看起来您可以简单地使用MKMapView 类centerCoordinate的属性- 文档说:

更改此属性中的值会使地图以新坐标为中心,而不会更改当前缩放级别。它还更新region属性中的值以反映新的中心坐标和保持当前缩放级别所需的新跨度值。

所以基本上,你只需要:

self.mapView.centerCoordinate = self.mapView.userLocation.location.coordinate;
于 2011-02-06T18:02:17.313 回答