как получить название города через CLlocationManager, используя широту и долготу в IOS?

Я пытаюсь получить адрес через CLLocationManager, используя широту и долготу, но он возвращает только название штата и страны, я также хочу город, я прикрепляю свой код, может ли кто-нибудь сказать мне, как я могу изменить свой код, чтобы также получить название города. мой код

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    currentLocation = [locations objectAtIndex:0];
    CLGeocoder *geocoder1 = [[CLGeocoder alloc] init];

     NSLog(@"Detected Location : %f, %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);

    //CLLocation *newLocation = [[CLLocation alloc]initWithLatitude:26.9260 longitude:75.8235];

    CLLocation *newLocation = [[CLLocation alloc]initWithLatitude:currentLocation.coordinate.latitude longitude:currentLocation.coordinate.longitude];

    [geocoder1 reverseGeocodeLocation:newLocation
                   completionHandler:^(NSArray *placemarks, NSError *error) {

                       if (error) {
                           NSLog(@"Geocode failed with error: %@", error);
                           return;
                       }

                       if (placemarks && placemarks.count > 0)
                       {
                           CLPlacemark *placemark = placemarks[0];

                           NSDictionary *addressDictionary =
                           placemark.addressDictionary;

                           NSLog(@"%@ ", addressDictionary);
                           NSString *address = [addressDictionary
                                                objectForKey:(NSString *)kABPersonAddressStreetKey];
                           NSString *city = [addressDictionary
                                             objectForKey:(NSString *)kABPersonAddressCityKey];
                           NSString *state = [addressDictionary
                                              objectForKey:(NSString *)kABPersonAddressStateKey];
                           NSString *zip = [addressDictionary
                                            objectForKey:(NSString *)kABPersonAddressZIPKey];


                           NSLog(@"%@ %@ %@ %@", address,city, state, zip);
                       }

                   }];
}

person vijay    schedule 22.07.2014    source источник
comment
На самом деле вы не получаете адрес через CLLocationManager. Вы получаете его через CLGeocoder (CLLocationManager просто дает вам координаты). Код выглядит нормально. Это может быть связано с координатами, которые CLGeocoder (Apple) не может хорошо геокодировать (похоже, Google в этом лучше). Координаты 26.9260, 75.8235?   -  person    schedule 22.07.2014


Ответы (3)


Попробуй это ..

-(NSString*)getAddressFromLatLong : (NSString *)latLng {
    //  NSString *string = [[Address.text stringByAppendingFormat:@"+%@",cityTxt.text] stringByAppendingFormat:@"+%@",addressText];
    NSString *esc_addr =  [latLng stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];
        NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
        NSMutableDictionary *data = [NSJSONSerialization JSONObjectWithData:[result dataUsingEncoding:NSUTF8StringEncoding]options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *dataArray = (NSMutableArray *)[data valueForKey:@"results" ];
        if (dataArray.count == 0) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Please Enter a valid address" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert show];
        }else{
            for (id firstTime in dataArray) {
                NSString *jsonStr1 = [firstTime valueForKey:@"formatted_address"];
                return jsonStr1;
            }
        }

    return nil;
}

Отправьте через запятую широту и долготу .. и попробуйте. Работает нормально.

Ссылка для справки Получение адреса по широте и долготе с помощью функции Apple в iOS и iPad

person Jogendra.Com    schedule 22.07.2014
comment
Я не хочу использовать API карты Google, есть ли способ получить название города с помощью CLLocationManager. - person vijay; 22.07.2014
comment
В последнем проекте я использовал это. ,, Но я не про CLLocationManager ... Пожалуйста, попробуйте поискать, если это возможно, тогда обязательно получите ... Попробуйте поискать больше,., .. - person Jogendra.Com; 22.07.2014

Вы используете k-константы из класса ABPerson из инфраструктуры AddressBook для ключей объекта CLGeocoder. Хотя некоторые могут совпадать, я уверен, что другие нет.

Ты можешь попробовать ...

NSMutableArray *addrArray = [[NSMutableArray alloc] init];
//to return address line(s)
addrArray = [NSMutableArray arrayWithArray: [p.addressDictionary objectForKey:@"FormattedAddressLines"]];
[addrArray removeLastObject]; //country name
NSString *addressString = [addrArray componentsJoinedByString:@" ,"];
#if DEBUG
                NSLog(@"Address: %@", addressString);
#endif
person gro    schedule 22.07.2014

Мы получим полный адрес на основе широты и долготы. Вот пример кода.

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

      CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
      [geocoder reverseGeocodeLocation:location
               completionHandler:^(NSArray *array, NSError *error){
    if (error){
        NSLog(@"Geocode failed with error: %@", error);
        return;
    }
    CLPlacemark *placemark = [array objectAtIndex:0];
     NSLog(@"City %@",placemark.subAdministrativeArea);
     NSLog(@"State %@",placemark.administrativeArea);

     }];
 }

Ниже я упомянул различные типы. Вы можете легко это проверить. Все они относятся к объектам класса CLPlacemark. Этот класс может быть доступен на CoreLocation Framework.

@property (nonatomic, readonly, copy, nullable) NSString *name; // eg. Apple Inc.
@property (nonatomic, readonly, copy, nullable) NSString *thoroughfare; // street name, eg. Infinite Loop
@property (nonatomic, readonly, copy, nullable) NSString *subThoroughfare; // eg. 1
@property (nonatomic, readonly, copy, nullable) NSString *locality; // city, eg. Cupertino
@property (nonatomic, readonly, copy, nullable) NSString *subLocality // neighborhood, common name, eg. Mission District
@property (nonatomic, readonly, copy, nullable) NSString *administrativeArea; // state, eg. CA
@property (nonatomic, readonly, copy, nullable) NSString *subAdministrativeArea; // City, eg. Santa Clara
@property (nonatomic, readonly, copy, nullable) NSString *postalCode; // zip code, eg. 95014
@property (nonatomic, readonly, copy, nullable) NSString *ISOcountryCode; // eg. US
@property (nonatomic, readonly, copy, nullable) NSString *country; // eg. United States
@property (nonatomic, readonly, copy, nullable) NSString *inlandWater; // eg. Lake Tahoe
@property (nonatomic, readonly, copy, nullable) NSString *ocean; // eg. Pacific Ocean
@property (nonatomic, readonly, copy, nullable) NSArray<NSString *> *areasOfInterest;

Что бы вы ни хотели, вы просто добавляете это и получаете результат. Вот ссылка ссылка.

person gireesh Chanti    schedule 23.03.2016