2009-12-14 25 views
1

我使用位置管理器在我的申請,我得到使用下面的代碼不準確location.I'm用於獲取位置是否需要給距離過濾器以獲取最佳位置?

locationManager.delegate = self; 
locationManager.desiredAccuracy = kCLLocationAccuracyBest; 

和didupdatetolocation方法我使用這個代碼。

LatitudeData = [[NSString alloc] initWithFormat:@"%f",newLocation.coordinate.latitude]; 
    LongitudeData = [[NSString alloc] initWithFormat:@"%f",newLocation.coordinate.longitude]; 
    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO; 
    [self insertNewLocationInDataBase]; 

我需要設置distancefilter嗎?我如何得到準確的位置?我想獲得準確的位置,然後將數據庫中的位置。

+1

已經有多個線程在這裏@ SO和很多帖子網上寬約這同一主題。尋找這些問題(以及他們的多種答案)將很適合你。 – KevinDTimm 2009-12-14 17:09:58

回答

8

在合理的時間內獲得核心位置的好結果需要謹慎小心。

問題是,一旦你開始更新,didUpdateToLocation將會觸發幾次。每次啓動時,位置應該更加準確。然而,你不知道它會觸發多少次,也不知道鎖定到你要求的精度會發生多快(如果它曾經發生過)。根據the documentation,如果超出最小閾值距離(由distanceFilter屬性指定),則會生成附加事件確定更準確的位置值。改變distanceFilter不會給你一個更好的位置(當然,除非你對精確的運動感興趣)。

有一些常見的設置可以幫助簡化這個過程,但是您可能需要根據所需的特定啓發式來擺弄這些。

  • 發送startUpdating來調用選擇器(可以像performSelector:afterDelay:一樣簡單)後設置一個計時器。將延遲設置爲您願意等待合理近似的最長時間。在該選擇器的方法中,我會檢查以確保該位置足夠準確以便放置在數據庫中,然後插入它。如果不是,我會提醒用戶。
  • didUpdateToLocation中,立即丟棄任何過舊的位置。 LocationManager通常會首先返回其位置的緩存值 - 並且可能會很舊。
  • didUpdateToLocation中,只需將最新結果保存到實例變量中,如果它不符合您的期望精度。
  • didUpdateToLocation,如果新位置足夠準確,取消延遲後執行選擇器,而是立即調用它。

這只是一個粗略的草圖,但它是一個非常靈活的設置,您可以輕鬆擴展以獲得所需的功能。

以下是如何工作的基本概述。這是從我的視圖控制器的一個配對下段,以只顯示相關部分的基礎知識:

- (void)viewWillAppear:(BOOL)animated { 
    [self.locationManager startUpdatingLocation]; 
    [self performSelector:@selector(finishUpdating) withObject:nil afterDelay:10.0]; 
    [super viewWillAppear:animated]; 
} 

- (void) locationManager:(CLLocationManager *)manager 
    didUpdateToLocation:(CLLocation *)newLocation 
      fromLocation:(CLLocation *)oldLocation { 
    /* Refuse updates more than a minute old */ 
    if (abs([newLocation.timestamp timeIntervalSinceNow]) > 60.0) { 
     return; 
    } 
    /* Save the new location to an instance variable */ 
    self.lastUpdatedLocation = newLocation; 

    /* If it's accurate enough, cancel the timer */ 
    if (newLocation.horizontalAccuracy < 20.0) { 
     [NSObject cancelPreviousPerformRequestsWithTarget:self 
               selector:@selector(finishUpdating) 
                object:nil] 
     /* And fire it manually instead */ 
     [self finishUpdating]; 
    } 
} 

- (void) finishUpdating { 
    /* Check the accuracy of self.lastUpdatedLocation, and either 
    * save it or alert the user that it's not accurate enough */ 
    [self.locationManager stopUpdatingLocation]; 
} 
+0

你能爲此發佈一個示例代碼嗎? – 2009-12-15 07:07:04

+0

非常感謝。現在告訴我設備需要多少時間才能獲取用戶位置。我剛剛測試了我的應用程序。在地圖視圖中,我沒有獲得藍色圓圈,而且當我使用位置管理器時,它顯示錯誤的位置。方法只被調用一次,我不知道它爲什麼不經常調用? – 2009-12-15 10:00:53

+0

也請在你的代碼中告訴我如何檢查self.lastUpdatedLocation的準確性?我想要最好的準確性,然後想將它保存在數據庫中。請多指導一下 – 2009-12-15 10:11:14