objective-c MKMapView中心位于用户位置

时间:2011-05-29 19:31:13

标签: ios objective-c animation gps mkmapview

我正在尝试放大用户位置作为屏幕的中心参考。我有这段代码:

MainViewController.h

#import <UIKit/UIKit.h>
#import "FlipsideViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

IBOutlet MKMapView *mapView;

@interface MainViewController : UIViewController <FlipsideViewControllerDelegate, MKMapViewDelegate> {
   MKMapView *mapView;
}
@property (nonatomic, retain) IBOutlet MKMapView *mapView;

MainViewController.m

@implementation MainViewController
@synthesize mapView;

 - (void)viewDidLoad {
    [super viewDidLoad];
    mapView = [[MKMapView alloc]
           initWithFrame:self.view.bounds
           ];
    mapView.showsUserLocation = YES;
    mapView.mapType = MKMapTypeHybrid;
    mapView.delegate = self;
    [self.view addSubview:mapView];
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta = 0.005;
    span.longitudeDelta = 0.005;
    CLLocationCoordinate2D location;
    location.latitude = userLocation.coordinate.latitude;
    location.longitude = userLocation.coordinate.longitude;
    region.span = span;
    region.center = location;
    [mapView setRegion:region animated:YES];
 }

现在我只在最后一行[mapView setRegion:region animated:YES]收到一个构建警告,说明:'mapView'的本地声明隐藏了实例变量'

2 个答案:

答案 0 :(得分:71)

执行mapView.showsUserLocation = YES;时,要求它检索用户位置。这不会立即发生。由于需要时间,地图视图会通过委托方法mapView:didUpdateUserLocation通知其委托用户位置可用。因此,您应该采用MKMapViewDelegate协议并实现该方法。您应该将所有放大代码移动到此方法。

设置代理

- (void)viewDidLoad {
    [super viewDidLoad];
    mapView = [[MKMapView alloc]
           initWithFrame:CGRectMake(0, 
                                    0,
                                    self.view.bounds.size.width, 
                                    self.view.bounds.size.height)
           ];
    mapView.showsUserLocation = YES;
    mapView.mapType = MKMapTypeHybrid;
    mapView.delegate = self;
    [self.view addSubview:mapView];
}

更新了委托方法

- (void)mapView:(MKMapView *)aMapView didUpdateUserLocation:(MKUserLocation *)aUserLocation {
    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta = 0.005;
    span.longitudeDelta = 0.005;
    CLLocationCoordinate2D location;
    location.latitude = aUserLocation.coordinate.latitude;
    location.longitude = aUserLocation.coordinate.longitude;
    region.span = span;
    region.center = location;
    [aMapView setRegion:region animated:YES];
}

答案 1 :(得分:3)

在您的界面中,您忘记继承MapViewDelegate -

#import <MapKit/MapKit.h>

@interface MainViewController : UIViewController <FlipsideViewControllerDelegate, MKMapViewDelegate> 
{
   MKMapView *mapView;
}
@property (nonatomic, retain) IBOutlet MKMapView *mapView;

休息似乎很好。