2012-07-02 25 views
1

我是新來的ObjC,我正在努力與CLGeocoder。我希望能夠使用reverseGeocodeLocation獲取一個字符串,其中包含用戶按下「完成」按鈕時傳遞給我的委託的用戶位置。CLGeocoder reverseGeocodeLocation。第一次在[地標計數= 0]?

因此,用戶觸發顯示MapViewController,我調用viewDidLoad中的reverseGeocodeLocation,但第一次調用[placemarks count = 0],並且我沒有地標來獲取我需要的信息。用戶第二次觸發MapViewController的顯示時,地標數組已被填充並且一切正常。

我懷疑這是與reverseGeocodeLocation做一個異步調用 - 但我不知道如何解決這個問題。我嘗試在網上搜索,但沒有任何東西似乎幫助我瞭解我在做什麼錯誤,以及我如何解決這個問題。提前致謝。

@interface MapViewController() 
@property (strong, nonatomic) CLGeocoder *geocoder; 
@property (readwrite, nonatomic) NSString *theLocationName; 
@end 

@implementation MapViewController 
@synthesize mapView, geocoder, delegate = _delegate, theLocationName = _theLocationName; 

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 

self.mapView.delegate=self; 
self.mapView.showsUserLocation = YES; 

[self theUserLocation]; 
} 

-(void)theUserLocation 
{ 
if (!geocoder) 
{ 
    geocoder = [[CLGeocoder alloc] init]; 
} 

MKUserLocation *theLocation; 
theLocation = [self.mapView userLocation]; 

[geocoder reverseGeocodeLocation:theLocation.location 
       completionHandler:^(NSArray* placemarks, NSError* error) 
{ 
    if ([placemarks count] > 0) 
    { 
     CLPlacemark *placemark = [placemarks objectAtIndex:0]; 

     [self setTheLocationName: placemark.locality]; 

    } 
}]; 

- (IBAction)done:(id)sender 
{ 

[[self delegate] mapViewControllerDidFinish:self locationName:[self theLocationName]]; 

} 

@end 

回答

2

所以用戶觸發一個MapViewController的顯示,我稱之爲reverseGeocodeLocation在viewDidLoad中但[標計數= 0]在該第一時間,我沒有PLAC emark獲取我需要的信息。用戶第二次觸發MapViewController的顯示時,地標數組已被填充並且一切正常。

這不是因爲呼叫是異步的 - 這是因爲您第一次撥打theUserLocation時,實際位置不可用。獲取用戶的位置不是即時的 - 這需要時間。但是,當地圖加載時,您要求用戶的地址爲,在大多數情況下,該地址不起作用。

您需要做的是掛入MKMapViewDelegate方法,該方法在位置更新時爲您提供回調。您可以使用它來檢查位置的準確性,並決定它是否足夠準確地反轉地理定位。

+0

謝謝您的回覆。接受我的道歉,因爲我仍在拼命試圖瞭解這是如何工作的。鑑於我沒有留出足夠的時間來了解用戶的位置,我認爲我會將該調用轉換爲[self theUserLocation]以執行完成按鈕。我的推理是,到目前爲止,地圖已經被顯示,並且正在顯示用戶放大的位置的引腳 - 所以用戶位置必須是已知的 - 但是這也不起作用。 –

+1

啊,剛剛纔明白了,因爲地理編碼器花了一些時間做一次經/緯度查找,所以剩下的Done代碼在地理編碼器可以提供答案之前執行。 –

+0

我已經實現了didUpdateUserLocation:方法,其中放置了所有用於放大用戶位置的代碼。我只是將[self theUserLocation]方法移到這裏 - 現在它工作了!我並不是100%確定這是水密的,因爲我擔心如果地理編碼器花了一段時間來做它的經緯度查找,用戶仍然可以在答案之前點擊完成按鈕? –

3

這是不準確的回答你的問題,但是,如果你可以從CLGeocoder除了切換到其他的解決方案比下面的函數可以幫助你從給定的緯度地址,經度

#define kGeoCodingString @"http://maps.google.com/maps/geo?q=%f,%f&output=csv" //define this at top 

-(NSString *)getAddressFromLatLon:(double)pdblLatitude withLongitude:(double)pdblLongitude 
{ 
    NSString *urlString = [NSString stringWithFormat:kGeoCodingString,pdblLatitude, pdblLongitude]; 
    NSError* error; 
    NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error]; 
    locationString = [locationString stringByReplacingOccurrencesOfString:@"\"" withString:@""]; 
    return [locationString substringFromIndex:6]; 
} 

信用: Selected Answer to this question

+0

謝謝您的回覆。我會牢記這一點,但我真的想了解CLGeocoder的工作原理:-) –

相關問題