2012-02-25 78 views
2

我想在啓動時將地圖縮放到當前用戶位置。我嘗試在viewDidLoad上使用mapView.userLocation.coordinate檢索用戶位置,但返回的座標爲(0,0),可能是因爲MapKit在啓動時不會「查找」用戶位置。iOS - 在應用程序啓動時縮放到當前用戶位置

我發現了一個實現方法didUpdateToLocation的解決方案。我做了以下內容:

- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    if (hasZoomedAtStartUp == NO) 
    { 
     [self zoomAtStartUp]; // my method to zoom the map 
     hasZoomedAtStartUp = YES; 
    } 
} 

我在.h文件中創建並在viewDidLoad中NO initialied它的hasZoomedAtStartUp變量。

此解決方案工作正常,但我想知道是否有另一種方法來做到這一點,沒有if語句。 IF與startUp相關的justo,所以我想刪除它,出於性能原因。

回答

5

我非常懷疑一個失敗的陳述是你需要擔心的表現。

您是否需要經常使用位置服務?如果不是,當您不再需要更新位置時,您可能會從調用stopUpdatingLocation獲得更大的收益。隨後,您甚至不會到達didUpdateToLocation,因爲您不再獲取新的位置數據。

+1

我一直需要位置服務,因爲我正在開發(實際上是爲了學習)基於地圖的應用程序。 If語句不是一個很大的性能問題,但是,因爲我總是需要它,所以它可能是。我想知道我是否可以在其他地方執行此任務,因爲我只需要一次(在startUp)。 – Beraldo 2012-02-26 15:59:08

+0

@尼克,不,我不同意你的觀點,如果有人不需要經常定位服務,那就沒有問題。我們只需要正確編程didUpdateToLocation和stopUpdatingLocation方法兩者。我們可以做到這一點,假設我們在特定的(A)上顯示CurrentLocation。然後,我們只需要從ViewLoadingTime調用didUpdateToLocation並在View中調用stopUpdatingLocation去disAppear( - (void )viewWillDisappear:(BOOL)動畫方法。)。 – Kamarshad 2012-02-29 10:41:13

2

您現在使用的方法-locationManager:didUpdateToLocation:fromLocation是對用戶位置進行任何操作的最佳位置。有幾件事情,我會盡你的不同。

首先,您接受第一次位置更新爲最佳。你可能要求一定的準確性,但要求它並不意味着該方法的newLocation是最好的。通常情況下,你會得到一個非常低的準確性,或者從過去的某個時間點的緩存位置。我會做的是檢查新的位置的年齡和準確性,只有當它的放大。

我會做的另一件事是關閉位置更新,無論是當更新具有良好的準確性在更新開始後30秒內。設置一個計時器將其關閉,當您關閉計時器時,請設置一個較長的計時器將其重新打開並再次檢查。

最後,請確保您已正確實施所有情況下的-locationManager:didFailWithError:。這一直是您提交應用程序時所測試的一件事情。如果它沒有失敗(例如,在飛行模式下),它可能會被拒絕。

圍繞堆棧溢出搜索技術和代碼來完成這些事情。

2

您可以隨時進行初始化並開始獲取位置更新。該CLLocationManager會通知您的委託,每當一個新的位置,接收 並設置在地圖上的區域該位置顯示

//Don't Forget To Adopt CLLocationManagerDelegate protocol 
//set up the Location manager  
locationManager = [[CLLocationManager alloc] init]; 
locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
locationManager.distanceFilter = DISTANCE_FILTER_VALUE; 
locationManager.delegate = self; 
[locationManager startUpdatingLocation] 

//WIll help to get CurrentLocation implement the CLLocationManager delegate 
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
// use this newLocation .coordinate.latitude 
} 

// set Span 
MKCoordinateSpan span; 
//You can set span for how much Zoom to be display like below 
span.latitudeDelta=.005; 
span.longitudeDelta=.005; 

//set Region to be display on MKMapView 
MKCoordinateRegion cordinateRegion; 
cordinateRegion.center=latAndLongLocation.coordinate; 
//latAndLongLocation coordinates should be your current location to be display 
cordinateRegion.span=span; 
//set That Region mapView 
[mapView setRegion:cordinateRegion animated:YES]; 
2

,您可根據「初始」委託執行,你可以縮放到位置後註銷,並註冊你的'普通'代表現在不需要整個縮放,如果有的話。

相關問題