2011-09-02 59 views
1

非常多的新手在這裏,請原諒無知。我花了一些時間試圖瞭解我失蹤的東西,但無法弄清楚。如何在特定位置居中,然後放大到當前位置

我的應用程序在加載時在華盛頓州的中心,但是當我嘗試縮放到用戶當前位置時,它將我置於北緯0經度0.如果我註釋掉「//啓動:WA中心」部分,用戶當前的位置,然後goToLocation工作正常。

我該如何讓它在華盛頓州的中心,然後在點擊goToLocation後縮放到用戶當前位置?

謝謝!

- (void)viewDidLoad { 

    [super viewDidLoad]; 
    [self loadOurAnnotations]; 
     [mapView setShowsUserLocation:NO]; 

// startup: center over WA 
    CLLocationCoordinate2D defaultCoordinate; 
    defaultCoordinate.latitude = 47.517201; 
    defaultCoordinate.longitude = -120.366211; 
    [mapView setRegion:MKCoordinateRegionMake(defaultCoordinate, MKCoordinateSpanMake(6.8, 6.8)) animated:NO]; 


} 


-(IBAction)goToLocation { 
    MKUserLocation *myLocation = [mapView userLocation]; 
    CLLocationCoordinate2D coord = [[myLocation location] coordinate]; 
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 350, 350); 
    [mapView setRegion:region animated:YES]; 

    [UIView beginAnimations:nil context:NULL]; 
    [UIView setAnimationDuration:1]; 
    [UIView commitAnimations]; 
} 

回答

1

首先,使用在MKMapViewuserLocation可言,你必須通過YESsetShowsUserLocation(不NO)。

接下來的事情是,在打開showsUserLocation之後,地圖視圖可能需要幾秒或更長時間來確定位置並設置userLocation。在此之前,該位置將爲零(給出0,0的座標)。

要真正瞭解userLocation何時準備(或更新),請實施didUpdateUserLocation委託方法。如果在確定用戶位置時出現問題,實施didFailToLocateUserWithError方法也很有幫助。

然而,在你的情況,你可以只是做在goToLocation方法如下:

MKUserLocation *myLocation = [mapView userLocation]; 
if (myLocation.location == nil) 
{ 
    NSLog(@"user location has not been determined yet"); 
    return; 
} 
CLLocationCoordinate2D coord = [[myLocation location] coordinate]; 
MKCoordinateRegion region = ... //rest of the code stays the same 

動畫聲明在該方法的最後什麼都不做,順便說一句。

+0

非常感謝你的幫助,安娜。我會修補這個。 – Rick