2013-05-20 19 views
11

voglio trovare nome attuale posizione dalla latitudine e longitudine,Get nome della località da latitudine e longitudine in iOS

Ecco il mio frammento di codice ho provato, ma il mio registro mostra valore nullo in tutti i posti tranne in placemark, placemark.ISOcountryCode e placemark.country

Voglio il valore di placemark.locality e placemark.subLocality ma mostra valori nulli.

- (void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 

    // this creates the CCLocationManager that will find your current location 
    locationManager = [[CLLocationManager alloc] init]; 
    locationManager.delegate = self; 
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; 
    [locationManager startUpdatingLocation]; 

} 

// this delegate is called when the app successfully finds your current location 
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    CLGeocoder *geocoder = [[CLGeocoder alloc] init]; 
    [geocoder reverseGeocodeLocation:locationManager.location 
        completionHandler:^(NSArray *placemarks, NSError *error) { 
         NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!"); 

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

         } 

         NSLog(@"placemarks=%@",[placemarks objectAtIndex:0]); 
         CLPlacemark *placemark = [placemarks objectAtIndex:0]; 

         NSLog(@"placemark.ISOcountryCode =%@",placemark.ISOcountryCode); 
         NSLog(@"placemark.country =%@",placemark.country); 
         NSLog(@"placemark.postalCode =%@",placemark.postalCode); 
         NSLog(@"placemark.administrativeArea =%@",placemark.administrativeArea); 
         NSLog(@"placemark.locality =%@",placemark.locality); 
         NSLog(@"placemark.subLocality =%@",placemark.subLocality); 
         NSLog(@"placemark.subThoroughfare =%@",placemark.subThoroughfare); 

        }]; 
} 

// this delegate method is called if an error occurs in locating your current location 
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 
{ 
    NSLog(@"locationManager:%@ didFailWithError:%@", manager, error); 
} 

Grazie In anticipo.

EDIT:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    CLGeocoder *geocoder = [[CLGeocoder alloc] init]; 

    CLLocation *currentLocation = newLocation; 

    if (currentLocation != nil) 
     NSLog(@"longitude = %.8f\nlatitude = %.8f", currentLocation.coordinate.longitude,currentLocation.coordinate.latitude); 

    // stop updating location in order to save battery power 
    [locationManager stopUpdatingLocation]; 


    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) 
    { 
     NSLog(@"Found placemarks: %@, error: %@", placemarks, error); 
     if (error == nil && [placemarks count] > 0) 
     { 
      CLPlacemark *placemark = [placemarks lastObject]; 

      // strAdd -> take bydefault value nil 
      NSString *strAdd = nil; 

      if ([placemark.subThoroughfare length] != 0) 
       strAdd = placemark.subThoroughfare; 

      if ([placemark.thoroughfare length] != 0) 
      { 
       // strAdd -> store value of current location 
       if ([strAdd length] != 0) 
        strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark thoroughfare]]; 
       else 
       { 
        // strAdd -> store only this value,which is not null 
        strAdd = placemark.thoroughfare; 
       } 
      } 

      if ([placemark.postalCode length] != 0) 
      { 
       if ([strAdd length] != 0) 
        strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark postalCode]]; 
       else 
        strAdd = placemark.postalCode; 
      } 

      if ([placemark.locality length] != 0) 
      { 
       if ([strAdd length] != 0) 
        strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark locality]]; 
       else 
        strAdd = placemark.locality; 
      } 

      if ([placemark.administrativeArea length] != 0) 
      { 
       if ([strAdd length] != 0) 
        strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark administrativeArea]]; 
       else 
        strAdd = placemark.administrativeArea; 
      } 

      if ([placemark.country length] != 0) 
      { 
       if ([strAdd length] != 0) 
        strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark country]]; 
       else 
        strAdd = placemark.country; 
      } 
     } 
    }]; 
} 
+2

È necessario utilizzare alcune API di terze parti come "API di Google Places". –

+1

Non è necessario utilizzare il servizio a pagamento di Google: questa funzionalità è integrata direttamente in iOS. Guarda CLLocation e CLPlacemark. Vi fornirà qualsiasi livello di granularità desiderato da coords, ad es. paese, città, regione, fuso orario, ecc. ecc. – samiles

risposta

11

I' Sto dando il frammento che sto usando per risolvere l'indirizzo. Includo anche il commento nel posto necessario per capire il codice per te. Inoltre, sentiti libero di porre qualsiasi domanda dallo snippet se non riesci a capire qualcosa.

Scrivi seguente frammento in didUpdateToLocation metodo

NSLog(@"didUpdateToLocation: %@", newLocation); 
CLLocation *currentLocation = newLocation; 

if (currentLocation != nil) 
    NSLog(@"longitude = %.8f\nlatitude = %.8f", currentLocation.coordinate.longitude,currentLocation.coordinate.latitude); 

// stop updating location in order to save battery power 
[locationManager stopUpdatingLocation]; 


// Reverse Geocoding 
NSLog(@"Resolving the Address"); 

// “reverseGeocodeLocation” method to translate the locate data into a human-readable address. 

// The reason for using "completionHandler" ---- 
    // Instead of using delegate to provide feedback, the CLGeocoder uses “block” to deal with the response. By using block, you do not need to write a separate method. Just provide the code inline to execute after the geocoding call completes. 

[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) 
{ 
    NSLog(@"Found placemarks: %@, error: %@", placemarks, error); 
    if (error == nil && [placemarks count] > 0) 
    { 
     placemark = [placemarks lastObject]; 

     // strAdd -> take bydefault value nil 
     NSString *strAdd = nil; 

     if ([placemark.subThoroughfare length] != 0) 
      strAdd = placemark.subThoroughfare; 

     if ([placemark.thoroughfare length] != 0) 
     { 
      // strAdd -> store value of current location 
      if ([strAdd length] != 0) 
       strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark thoroughfare]]; 
      else 
      { 
      // strAdd -> store only this value,which is not null 
       strAdd = placemark.thoroughfare; 
      } 
     } 

     if ([placemark.postalCode length] != 0) 
     { 
      if ([strAdd length] != 0) 
       strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark postalCode]]; 
      else 
       strAdd = placemark.postalCode; 
     } 

     if ([placemark.locality length] != 0) 
     { 
      if ([strAdd length] != 0) 
       strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark locality]]; 
      else 
       strAdd = placemark.locality; 
     } 

     if ([placemark.administrativeArea length] != 0) 
     { 
      if ([strAdd length] != 0) 
       strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark administrativeArea]]; 
      else 
       strAdd = placemark.administrativeArea; 
     } 

     if ([placemark.country length] != 0) 
     { 
      if ([strAdd length] != 0) 
       strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark country]]; 
      else 
       strAdd = placemark.country; 
     } 

Dove strAdd tornerà indirizzo utilizzando la geolocalizzazione ..

di una programmazione !!

+0

' currentLocation' è sconosciuto – Krunal

+0

currentLocation è newLocation da questo metodo. Controlla la mia risposta aggiornata –

+0

hey Ho fatto tutto per te. Devi solo sostituire il tuo codice in - (void) locationManager: (CLLocationManager *) manager didUpdateToLocation: (CLLocation *) newLocation fromLocation: (CLLocation *) oldLocation with mine, e avrai la tua risposta. –

0

Se la posizione che si sta cercando di ottenere è elencato in questa lista, allora c'è qualcosa di sbagliato nel codice ..

http://developer.apple.com/library/ios/#technotes/tn2289/_index.html#//apple_ref/doc/uid/DTS40011305

altrimenti CLGeoCoder non ha indirizzi verso altri paesi.

Ho affrontato lo stesso problema quindi l'ho usato per ottenere l'indirizzo .. Fornisce un indirizzo molto preciso.

http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true_or_false

0

Prima di tutto, luoghi di filtro in didUpdateToLocation per impedire l'uso cache o posizioni sbagliate per geocoding

NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow]; 

if (abs(locationAge) > 5.0) return; 

if (newLocation.horizontalAccuracy < 0) return; 

Inoltre, cercare di spostare il metodo reverseGeoCoding lontano da didUpdateToLocation

+0

esempio dimostrativo di mela mostra anche valore nullo, perché è un'idea? 'http: //developer.apple.com/library/ios/#samplecode/GeocoderDemo/Introduction/Intro.html # // apple_ref/doc/uid/DTS40011097' – Krunal

0

Una volta che avete latitude, longitude valori di una posizione è possibile utilizzare CLGeocoder ecco un tutorial che potrebbe aiutare.

+0

E può essere utilizzato per iOS 5 e versioni successive –

+0

esempio di Apple mostra anche valore nullo, perché è qualche idea? 'Http://developer.apple.com/library/ios/# samplecode/GeocoderDemo/Introduzione/Intro.html # // apple_ref/doc/uid/DTS40011097' – Krunal

+0

campione dimostrativo di Apple mostra anche valore nullo, perché è un'idea? 'http: //developer.apple.com/library/ios/#samplecode/GeocoderDemo/Introduction/Intro.html # // apple_ref/doc/uid/DTS40011097' – Krunal

0

utilizzare questa API per ottenere i dati e passare valori lat e lunghi.

API for Geo location

+0

Apple sta inoltre mostrando valore nullo, perché è qualche idea? 'http: //developer.apple.com/library/ios/#samplecode/GeocoderDemo/Introduction/Intro.html # // apple_ref/doc/uid/DTS40011097' – Krunal

9

metodo con il blocco completo:

typedef void(^addressCompletion)(NSString *); 

-(void)getAddressFromLocation:(CLLocation *)location complationBlock:(addressCompletion)completionBlock 
{ 
    __block CLPlacemark* placemark; 
    __block NSString *address = nil; 

    CLGeocoder* geocoder = [CLGeocoder new]; 
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) 
    { 
     if (error == nil && [placemarks count] > 0) 
     { 
      placemark = [placemarks lastObject]; 
      address = [NSString stringWithFormat:@"%@, %@ %@", placemark.name, placemark.postalCode, placemark.locality]; 
      completionBlock(address); 
     } 
    }]; 
} 

Questo è come usarlo:

CLLocation* eventLocation = [[CLLocation alloc] initWithLatitude:_latitude longitude:_longitude]; 

[self getAddressFromLocation:eventLocation complationBlock:^(NSString * address) { 
     if(address) { 
      _address = address; 
     } 
    }]; 
0

Prova questa

[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) { 
     //..NSLog(@"Found placemarks: %@, error: %@", placemarks, error); 
     if (error == nil && [placemarks count] > 0) { 
      placemark = [placemarks lastObject]; 
      lblgetaddrees.text = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@", 
            placemark.subThoroughfare, placemark.thoroughfare, 
            placemark.postalCode, placemark.locality, 
            placemark.administrativeArea, 
            placemark.country]; 
     } else { 
      //..NSLog(@"%@", error.debugDescription); 
     } 
    } ]; 
3

ho implementato la soluzione di Niru in Swift 3, distacco qui qualcuno dovrebbe bisogno:

let geocoder = CLGeocoder() 
geocoder.reverseGeocodeLocation(self.location!) { (placemarksArray, error) in 

    if (placemarksArray?.count)! > 0 { 

     let placemark = placemarksArray?.first 
     let number = placemark!.subThoroughfare 
     let bairro = placemark!.subLocality 
     let street = placemark!.thoroughfare 

     self.addressLabel.text = "\(street!), \(number!) - \(bairro!)" 
    } 
} 
Problemi correlati