2014-07-01 9 views
8

Mam bieżącą lokalizację na podstawie wartości długości i szerokości geograficznej, a następnie mam również wiele miejsc na mapie google przy użyciu adnotacji. Teraz chcę uzyskać wartości długości i szerokości geograficznej na podstawie adresu (tj. Ulicy, miasta i hrabstwa). Proszę podać wskazówki, jak można to osiągnąć.Pobierz szerokość i długość geograficzną w oparciu o adres przy użyciu klasy Geocoder w systemie iOS

Do tej pory, to co próbowałem: -

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 
@synthesize streetField = _streetField, cityField = _cityField, countryField = _countryField, fetchCoordinatesButton = _fetchCoordinatesButton, nameLabel = _nameLabel, coordinatesLabel = _coordinatesLabel; 
@synthesize geocoder = _geocoder; 


- (void)viewDidLoad 
{ 

    [super viewDidLoad]; 
    _streetField.delegate=self; 
    _cityField.delegate=self; 
    _countryField.delegate=self; 

    // Do any additional setup after loading the view, typically from a nib. 
} 

- (IBAction)fetchCoordinates:(id)sender { 
    NSLog(@"Fetch Coordinates"); 
    if (!self.geocoder) { 
      NSLog(@"Geocdoing"); 
     self.geocoder = [[CLGeocoder alloc] init]; 
    } 

    NSString *address = [NSString stringWithFormat:@"%@ %@ %@", self.streetField.text, self.cityField.text, self.countryField.text]; 
    NSLog(@"GET Addres%@",address); 

    self.fetchCoordinatesButton.enabled = NO; 

    [self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) { 
      NSLog(@"Fetch Gecodingaddress"); 
     if ([placemarks count] > 0) { 
      CLPlacemark *placemark = [placemarks objectAtIndex:0]; 

      NSLog(@"GET placemark%@",placemark); 

      CLLocation *location = placemark.location; 

      NSLog(@"GET location%@",location); 

      CLLocationCoordinate2D coordinate = location.coordinate; 


      self.coordinatesLabel.text = [NSString stringWithFormat:@"%f, %f", coordinate.latitude, coordinate.longitude]; 

      NSLog(@"CoordinatesLabel%@",self.coordinatesLabel.text); 


      if ([placemark.areasOfInterest count] > 0) { 
       NSString *areaOfInterest = [placemark.areasOfInterest objectAtIndex:0]; 
       self.nameLabel.text = areaOfInterest; 
       NSLog(@"NameLabe%@",self.nameLabel.text); 
      } 
     } 

     self.fetchCoordinatesButton.enabled = YES; 
    }]; 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 
-(BOOL)textFieldShouldReturn:(UITextField *)textField 
{ 
    [textField resignFirstResponder]; 
    return YES; 
} 
@end 

Powyższy kod nie działa mi dać swobodę i longitude.Need pomocy na to, co robię źle tutaj lub jeśli brakuje mi na czymś.

Dzięki z góry.

+0

użyj tego linku to jest nadzieja dla Ciebie http://stackoverflow.com/questions/21595538/get-latitude-and-longitude- based- on-zip-using-geocoder-class-in-ios/21595688 # 21595688 –

+0

@ Anbu.Karthik Potrzebuję uzyskać wartości długości i szerokości geograficznej na podstawie adresu.Twój kod na podstawie kodu pocztowego. próbowałem ci kodu podałem nazwę mojego miasta i nazwę kraju do adresu URL, ale to nie działa Proszę dać mi jakiś pomysł – user3792517

Odpowiedz

21

EDIT:

Przed użyciem tej kontroli z systemów iOS 8 updation

NSLocationAlwaysUsageDescription 
NSLocationWhenInUseUsageDescription 

To za długo i coraz łac oparciu obszar użytkownika, jak nazwa ulicy, nazwę państwa, kraju.

-(CLLocationCoordinate2D) getLocationFromAddressString: (NSString*) addressStr { 
    double latitude = 0, longitude = 0; 
    NSString *esc_addr = [addressStr 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]; 
    if (result) { 
     NSScanner *scanner = [NSScanner scannerWithString:result]; 
     if ([scanner scanUpToString:@"\"lat\" :" intoString:nil] && [scanner scanString:@"\"lat\" :" intoString:nil]) { 
      [scanner scanDouble:&latitude]; 
      if ([scanner scanUpToString:@"\"lng\" :" intoString:nil] && [scanner scanString:@"\"lng\" :" intoString:nil]) { 
       [scanner scanDouble:&longitude]; 
      } 
     } 
    } 
    CLLocationCoordinate2D center; 
    center.latitude=latitude; 
    center.longitude = longitude; 
    NSLog(@"View Controller get Location Logitute : %f",center.latitude); 
    NSLog(@"View Controller get Location Latitute : %f",center.longitude); 
    return center; 

} 

wywołać metodę jak to w metodzie viewDidLoad lub gdzieś według projektu

[self getLocationFromAddressString:@"chennai"]; 

prostu przekazać to w przeglądarce http://maps.google.com/maps/api/geocode/json?sensor=false&address=chennai

i trzeba będzie formacie JSON z lat i lon

http://maps.google.com/maps/api/geocode/json?sensor=false&[email protected]"your city name here" 




NSString *address = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@ %@ %@", self.streetField.text, self.cityField.text, self.countryField.text]; 

the us wiek tej metody ....

CLLocationCoordinate2D center; 
     center=[self getLocationFromAddressString:@"uthangarai"]; 
     double latFrom=&center.latitude; 
     double lonFrom=&center.longitude; 

    NSLog(@"View Controller get Location Logitute : %f",latFrom); 
     NSLog(@"View Controller get Location Latitute : %f",lonFrom); 
+0

dzięki za odpowiedź, ale gdzie to umieszczone Adres – user3792517

+0

wystarczy podać nazwę miasta ... – karthikeyan

+0

. i będzie format json i pokazuje sformatowany adres z twoim miastem, krajem – karthikeyan

0
- (IBAction)forwardButton:(id)sender 
{ 
    if([self.address.text length]) 
    { 
     NSString *place = self.address.text; 
     CLGeocoder *geocoder = [[CLGeocoder alloc] init]; 
     __unsafe_unretained RTGeoCoderViewController *weakSelf = self; 
     [geocoder geocodeAddressString:place completionHandler:^(NSArray* placemarks, NSError* error) 
     { 
      NSLog(@"completed"); 
      if (error) 
      { 
       NSLog(@"error = %@", error); 
       dispatch_async(dispatch_get_main_queue(), 
           ^{ 
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[self errorMessage:error.code] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; 
            [alert show]; 
           }); 
      } 
      else 
      { 
       NSLog(@"%@",placemarks); 
      } 
     }]; 
    } 
} 
3

Spróbuj tego,

NSString *address = [NSString stringWithFormat:@"%@,%@,%@", self.streetField.text, self.cityField.text,self.countryField.text];  

[self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) 
{ 
    if(!error) 
    { 
     CLPlacemark *placemark = [placemarks objectAtIndex:0]; 
     NSLog(@"%f",placemark.location.coordinate.latitude); 
     NSLog(@"%f",placemark.location.coordinate.longitude); 
     NSLog(@"%@",[NSString stringWithFormat:@"%@",[placemark description]]); 
    } 
    else 
    { 
     NSLog(@"There was a forward geocoding error\n%@",[error localizedDescription]); 
    } 
} 
]; 
+0

Nie dostaję szerokości i długości geograficznej – user3792517

+0

Przyjeżdżam tutaj, lub próbuję użyć Google api "http: //maps.googleapis. com/maps/api/geocode/json? sensor = true i adres = ". Dodaj ciąg adresu, zastępując spacje przez + do powyższego api i przeanalizuj odpowiedź JSON – abhi

8

Ktoś szuka rozwiązania Swift 2.0 można używać poniżej:

let address = "1 Infinite Loop, CA, USA" 
     let geocoder = CLGeocoder() 

     geocoder.geocodeAddressString(address, completionHandler: {(placemarks, error) -> Void in 
      if((error) != nil){ 
       print("Error", error) 
      } 
      if let placemark = placemarks?.first { 
       let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate 
       coordinates.latitude 
       coordinates.longitude 
       print("lat", coordinates.latitude) 
       print("long", coordinates.longitude) 


      } 
     }) 
0

Spróbuj

- (void)getAddressFromAdrress:(NSString *)address withCompletationHandle:(void (^)(NSDictionary *))completationHandler { 


       CLGeocoder *geoCoder = [[CLGeocoder alloc] init]; 
      //Get the address through geoCoder 
      [geoCoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) { 


       if ([placemarks count] > 0 && !error) { 

        //get the address from placemark 
        CLPlacemark *placemark = [placemarks objectAtIndex:0]; 
        NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "]; 
        CLLocation *location = placemark.location; 
        CLLocationCoordinate2D coordinate = location.coordinate; 
        _latitudeUserLocation = coordinate.latitude; 
        _longitudeUserLocation = coordinate.longitude; 
        NSString *postalCode = placemark.addressDictionary[(NSString*)kABPersonAddressZIPKey]; 
        if (postalCode == nil) postalCode = @""; 
        if (locatedAt == nil) locatedAt = @""; 
        NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: 
               postalCode    ,kPostalCode, 
               locatedAt    ,kFullAddress, 
               nil]; 
        completationHandler(dictionary); 

       } else { 

        completationHandler(nil); 
       } 
      }]; 
} 
4

Swift

public func getLocationFromAddress(address : String) -> CLLocationCoordinate2D { 
     var lat : Double = 0.0 
     var lon : Double = 0.0 

     do { 

      let url = String(format: "https://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", (address.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)) 
      let result = try Data(contentsOf: URL(string: url)!) 
      let json = JSON(data: result) 

      lat = json["results"][0]["geometry"]["location"]["lat"].doubleValue 
      lon = json["results"][0]["geometry"]["location"]["lng"].doubleValue 

     } 
     catch let error{ 
      print(error) 
     } 

     return CLLocationCoordinate2D(latitude: lat, longitude: lon) 
    } 

użyłem SwiftyJSON ale można analizować odpowiedzi JSON jednak chcesz

0

Korzystanie Dashrath kod, można użyć ciąg adresów dodać GMSMarker

(w szybkiej 4)

func getLocationFromAddress(address : String, localName: String) { 
     let geocoder = CLGeocoder() 
     var coordinates = CLLocationCoordinate2D() 
     geocoder.geocodeAddressString(address, completionHandler: {(placemarks, error) -> Void in 
      if((error) != nil){ 
       print("Error", error!) 
      } 
      if let placemark = placemarks?.first { 
       coordinates = placemark.location!.coordinate 
       let marker = GMSMarker(position: coordinates) 
       marker.title = localName 
       marker.map = self.mapView 
      } 
     }) 
    } 
Powiązane problemy