Как вы центрируете карту MKMapView визуально, когда местоположение пользователя известно или изменяется?

Я прочитал и выполнил инструкции на Как увеличить MKMapView до текущего местоположения пользователя без CLLocationManager?

Однако, хотя я и получаю текущее местоположение пользователя, я не могу сделать карту визуально центрированной там.

Например, в функции viewDidLoad, как я могу заставить карту визуально центрироваться вокруг известного пользователю местоположения? Я вставил код из CurrentLocation ниже (см. Комментарий XXX в viewDidLoad


#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

person DeShawn Terrell    schedule 06.02.2011    source источник


Ответы (1)


Похоже, вы можете просто использовать свойство centerCoordinate объекта MKMapView class - в документации сказано:

При изменении значения этого свойства карта центрируется по новой координате без изменения текущего уровня масштабирования. Он также обновляет значения в свойстве region, чтобы отразить новую координату центра и новые значения диапазона, необходимые для поддержания текущего уровня масштабирования.

В общем, вы просто делаете:

self.mapView.centerCoordinate = self.mapView.userLocation.location.coordinate;
person Tim    schedule 06.02.2011
comment
вам нужно либо mapView.userLocation.coordinate, либо mapView.userLocation.location.coordinate. Свойство centerCoordinate имеет тип CLLocationCoordinate2D. - person Anurag; 06.02.2011
comment
Спасибо, парни. Так что делаем self.mapView.centerCoordinate = self.mapView.userLocation.location.coordinate; не работает из viewDidLoad. Он работает в другом месте (например, в reverseGeocodeCurrentLocation) - DT - person DeShawn Terrell; 06.02.2011
comment
Есть ли какая-то особая причина, по которой он должен быть внутри viewDidLoad? - person Tim; 07.02.2011
comment
Вы также можете использовать [self.mapView setCenterCoordinate: self.mapView.userLocation.location.coordinate animated: YES], чтобы получить этот анимированный - person dulgan; 15.04.2013
comment
Вы также можете использовать setRegion: animated: вместо простой установки координаты центра, поскольку вы можете захотеть, чтобы карта увеличивалась / отдалялась, а также перемещалась туда, где находится маркер местоположения пользователя. - person shim; 06.10.2014