2011-03-05 69 views
0

我的MapView並不縮放到我的用戶的位置。請你能指出錯誤:MapView類不縮放用戶位置

- (void)viewDidLoad { 
[super viewDidLoad]; 
mapView = [[MKMapView alloc] init]; 
mapView.showsUserLocation = YES; 
mapView.mapType = MKMapTypeHybrid; 
mapView.delegate = self; 

[self performSelector:@selector(startupZoom) withObject:nil afterDelay:1.25]; 
} 
- (void)startupZoom { 
MKCoordinateRegion region; 
MKCoordinateSpan span; 
span.latitudeDelta=0.2; 
span.longitudeDelta=0.2; 
CLLocationCoordinate2D location=mapView.userLocation.coordinate; 
location.latitude=mapView.userLocation.coordinate.latitude; 
location.longitude=mapView.userLocation.coordinate.longitude; 
region.span=span; 
region.center=location; 
[mapView setRegion:region animated:TRUE]; 
[mapView regionThatFits:region]; 
NSLog(@"%f, %f", mapView.userLocation.coordinate.latitude, mapView.userLocation.coordinate.longitude); 
} 

回答

0

正在創建的MapView,但其框架沒有設置,它不是被添加視圖控制器的視圖的子視圖。

更改ALLOC + INIT線(改變尺寸需要):但是

[self.view addSubview:mapView]; 

需要注意的是,最好使用:

mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 300)]; 

然後performSelector前行,添加此的MKMapView的didUpdateUserLocation委託方法放大到用戶的位置,而不是像1.25秒一些任意的,固定的時間間隔之後假定用戶位置將是可用的。

例如,刪除performSelector線並實現didUpdateUserLocation:使用didUpdateUserLocation方法

- (void)mapView:(MKMapView *)mapView 
      didUpdateUserLocation:(MKUserLocation *)userLocation 
{ 
    [self startupZoom]; 
} 

唯一可能的問題是,它會被稱爲每當用戶的位置變化,所以如果你只是想放大一次在啓動時,您需要添加一個BOOL標誌ivar並相應地檢查/設置它。

+0

無關,但另一件事是在調用regionThatFits是不對的。該regionThatFits方法_returns_的MKCoordinateRegion(它不是一個空洞的方法),所以調用它的方式並不做任何事情。但是,無論如何您都不需要調用regionThatFits,因爲setRegion已經根據需要照顧到區域。 – Anna 2011-03-05 04:15:56

+0

你好安娜,一旦你獲得用戶位置,你如何禁用!因爲使用委託,它會連續調用。我只想打一次電話。 – 2012-11-04 03:43:25

+0

@ user1724168:如果使用showsUserLocation = YES,它在didUpdateUserLocation設置爲NO。如果使用CLLocationManager,請在didUpdateToLocation/didUpdateLocations中調用stopUpdatingLocation。 – Anna 2012-11-04 13:04:21

相關問題