2011-08-04 61 views
0

我的最終目標是每當位置發生變化時,我都需要向緯度服務器發送緯度和緯度。獲取更改位置的最佳方式iPhone sdk?

我使用下面的代碼,每隔2分鐘向網絡服務器發送一個設備的經緯度,但它並沒有給出正確的緯度和經度,因爲位置發生變化。

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation 
*)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow]; 
    NSLog(@"Location Age%@",[NSString stringWithFormat:@"%d",locationAge]); 
    if (locationAge > 5) return; 

    // test that the horizontal accuracy does not indicate an invalid measurement  
    if (newLocation.horizontalAccuracy < 0) return; 

    NSString *stringUrl; 
    // BOOL check = FALSE; 
    NSLog(@"Before condition condition"); 
    if(bestEffortAtLocation == nil || bestEffortAtLocation.horizontalAccuracy > newLocation.horizontalAccuracy){ 
     NSLog(@"condition"); 
     self.bestEffortAtLocation = newLocation; 

     if (newLocation.horizontalAccuracy <= locmanager.desiredAccuracy) { 
      // we have a measurement that meets our requirements, so we can stop updating the location 
      // IMPORTANT!!! Minimize power usage by stopping the location manager as soon as possible. 
      [locmanager stopUpdatingLocation]; 
      locmanager.delegate = nil; 
     } 
     //check = TRUE; 
    } 

    stringUrl = [NSString stringWithFormat:URLSAVELAT,stringUserId,[NSString stringWithFormat:@"%g",self.bestEffortAtLocation.coordinate.latitude],[NSString stringWithFormat:@"%g",self.bestEffortAtLocation.coordinate.longitude]];} 

對於位置管理器,我使用下面的代碼

{ 
locmanager = [[CLLocationManager alloc] init]; 
[locmanager setDelegate:self]; 
locmanager.distanceFilter = 10.0; 
//locmanager.distanceFilter = kCLDistanceFilterNone; 
[locmanager setDesiredAccuracy:kCLLocationAccuracyBest]; 
[locmanager startUpdatingLocation]; 
}  

任何,哪怕是很小的幫助將不勝感激,感謝ü提前

+0

可能導致問題的一件事是,提供給iPhone的GPS數據不是很準確。當我使用它的時候,我有時在靜止的時候獲得了大約50-100米的變化值(儘管這並不是每次更新)。這可能是什麼導致你的問題。如果您需要非常準確,那麼您可能不得不使用羅盤和陀螺儀模擬真實世界中設備的運動,並將其與GPS數據進行比較,以更好地估計實際運動。希望有所幫助! – msgambel

+0

您能否爲我提供任何來源或參考資料,以便使用此功能進行位置跟蹤。 –

+0

顯然,在iOS 4.0及更高版本中,您現在可以使用常量kCLLocationAccuracyBestForNavigation以獲得更高的準確性,但它確實提到應在設備插入時使用它。可以在此處找到它:http://developer.apple。 COM /庫/ IOS /#文檔/ CoreLocation /參考/ CoreLocationConstantsRef /參考/的reference.html – msgambel

回答

3

您應該使用從位置更新回調API和使用updateLocation方法:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { 
if([self.delegate conformsToProtocol:@protocol(CoreLocationControllerDelegate)]) { 
    [self.delegate locationUpdate:newLocation]; 
} 
} 

然後在視圖 - 控制做到這一點:

- (void)locationUpdate:(CLLocation *)location { 

//DO WHATEVER YOU WANT HERE, INCLUDING SENDING TO SERVER 

} 

您還需要定義兩個協議的方法,其中之一是locationUpdate:

@protocol CoreLocationControllerDelegate 
@required 

- (void)locationUpdate:(CLLocation *)location; 
- (void)locationError:(NSError *)error; 

@end 

我不建議這樣做所有你在做didUpdateLocation:方法。

相關問題