2012-11-21 343 views
0

我試過這個代碼獲取基於地理位置的值,但無法獲取城市名稱。我如何獲得城市名稱?如何在iphone中獲取地理位置城市名稱?

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    double lati = newLocation.coordinate.latitude; 
    _geo_coder_latitude_lbl.text= [[NSString stringWithFormat:@"%f",lati] retain]; 
    _geocoder_latitude_str=_geo_coder_latitude_lbl.text; 
    NSLog(@"print lat;%@",_geocoder_latitude_str); 
    double longi = newLocation.coordinate.longitude; 
    _geocoder_longitude_lbl.text= [[NSString stringWithFormat:@"%f",longi] retain]; 
    _geocoder_longitude_str=_geocoder_longitude_lbl.text; 
    NSLog(@"print lat;%@",_geocoder_longitude_str); 
    [self._geocoder reverseGeocodeLocation: locationManager.location completionHandler: 
^(NSArray *placemarks, NSError *error) 
{ 

    //Get address 
    CLPlacemark *placemark = [placemarks objectAtIndex:0]; 

    NSLog(@"Placemark array: %@",placemark.addressDictionary); 

    //String to address 

    _located_address = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "]; 

    //Print the location in the console 

    NSLog(@"Currently address is: %@",_located_address); 

    // _ex_map_address_lbl.text=_located_address; 

}]; 

    [self _storeList_json_parser]; 

} 

回答

2

見CLPlacemark docs[CLPlacemark locatity]將返回與地標相關的城市名稱。

入住此示例代碼:

CLGeocoder *geocoder = [[CLGeocoder alloc] init]; 
double lati = 45.46433; 
double longi = 9.18839; 

CLLocation *location = [[CLLocation alloc] initWithCoordinate:CLLocationCoordinate2DMake(lati, longi) 
                altitude:0 
              horizontalAccuracy:0 
              verticalAccuracy:0 
                timestamp:[NSDate date]]; 

[geocoder reverseGeocodeLocation:location completionHandler: 
    ^(NSArray *placemarks, NSError *error) 
    { 
     CLPlacemark *placemark = [placemarks lastObject]; 
     if (error || !placemark) 
      return; 

     NSString *city = placemark.locality; 
     if (!city) 
      city = placemark.subAdministrativeArea; 

     NSLog(@"City for location: %@", city); 
}]; 
+0

是的,我試試這個placemark.locality一段時間,城市名的來源,但一段時間placemark.locality響應顯示空值。如何我能得到城市名稱標準響應。 –

+0

如果使用subAdministrativeArea進行回退,該怎麼辦?查看更新的代碼。 –

+0

精雅,但有些標域響應顯示.eg它的顯示空值:標地點:哥印拜陀 標subLocality:(空) 標subAdministrativeArea:(空) 標通途:Siddhapudur路 標subThoroughfare:(空) 標名稱:Siddhapudur路 標記國家:印度 Placemark administrativeAreay:泰米爾納德邦 城市位置:哥印拜陀 笏它的顯示空值的原因有時? –

相關問題