2012-05-09 29 views
16

Tôi muốn có tên Thành phố hiện tại trong Ứng dụng iPhone của mình.iPhone - Nhận tên thành phố từ Latitude và Longtiude

Tôi hiện đang nhận được vĩ độ và kinh độ bằng cách sử dụng CLLocationManager và hơn tôi đang chuyển tọa độ của tôi vào CLGeocoder.

CLGeocoder * geoCoder = [[CLGeocoder alloc] init]; 
    [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) { 
     for (CLPlacemark * placemark in placemarks) { 
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Current City" message:[NSString stringWithFormat:@"Your Current City:%@",[placemark locality]] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel", nil]; 
      [alert show]; 
     } 
    }]; 

Tính năng này hoạt động tốt trong iOS 5.0 nhưng không hoạt động trong iOS 4.3.

Là một thay thế, tôi bắt đầu sử dụng dịch vụ Web Google

-(void)findLocationFor:(NSString *)latitudeStr 
      andLontitude:(NSString *)longtitudeStr{ 
    if ([self connectedToWiFi]){ 
     float latitude = [latitudeStr floatValue]; 
     float longitude = [longtitudeStr floatValue]; 
     NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys: 
              [NSString stringWithFormat:@"%f,%f", latitude, longitude], @"latlng", nil]; 
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://maps.googleapis.com/maps/api/geocode/json"]]; 
     [parameters setValue:@"true" forKey:@"sensor"]; 
     [parameters setValue:[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode] forKey:@"language"]; 
     NSMutableArray *paramStringsArray = [NSMutableArray arrayWithCapacity:[[parameters allKeys] count]]; 

     for(NSString *key in [parameters allKeys]) { 
      NSObject *paramValue = [parameters valueForKey:key]; 
      [paramStringsArray addObject:[NSString stringWithFormat:@"%@=%@", key, paramValue]]; 
     } 

     NSString *paramsString = [paramStringsArray componentsJoinedByString:@"&"]; 
     NSString *baseAddress = request.URL.absoluteString; 
     baseAddress = [baseAddress stringByAppendingFormat:@"?%@", paramsString]; 
     [request setURL:[NSURL URLWithString:baseAddress]]; 

     NSError  *error = nil; 
     NSURLResponse *response = nil; 
     NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
     if (response == nil) { 
      if (error != nil) { 
      } 
     } 
     else { 
      NSDictionary *responseDict = [returnData objectFromJSONData]; 
      NSArray *resultsArray = [responseDict valueForKey:@"results"]; 
      NSMutableArray *placemarksArray = [NSMutableArray arrayWithCapacity:[resultsArray count]]; 
      for(NSDictionary *placemarkDict in resultsArray){ 
       NSDictionary *coordinateDict = [[placemarkDict valueForKey:@"geometry"] valueForKey:@"location"]; 

       float lat = [[coordinateDict valueForKey:@"lat"] floatValue]; 
       float lng = [[coordinateDict valueForKey:@"lng"] floatValue]; 

       NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 
       [dict setObject:[NSString stringWithFormat:@"%.f",lat] forKey:@"latitude"]; 
       [dict setObject:[NSString stringWithFormat:@"%.f",lng] forKey:@"longitude"]; 
       [dict setObject:[placemarkDict objectForKey:@"formatted_address"] forKey:@"address"]; 

       [placemarksArray addObject:dict]; 
       [dict release]; 
      } 
      NSDictionary *placemark = [placemarksArray objectAtIndex:0]; 
     } 
    } 
} 

Nhưng câu trả lời mà tôi nhận được là quá dài, có nghĩa là tôi vẫn không thể có được tên thành phố bởi vì trong một số trường hợp dịch vụ web này cung cấp tất cả các thông tin khác liên quan đến tọa độ mong đợi tên thành phố.

Có thể bất kỳ ai giúp tôi không?

Trả lời

23

Theo tài liệu CLGeocoder không hoạt động bên dưới iOS5. Bạn cần phải thực hiện một tuyến đường khác để hỗ trợ cả iOS4 và iOS5.

Bạn có thể xem MKReverseGeocoder, tuy nhiên nó không được chấp nhận trong iOS5 nhưng vẫn sẽ phục vụ mục đích. Để xác nhận, bạn có thể kiểm tra so called question

+(NSString *)getAddressFromLatLon:(double)pdblLatitude withLongitude:(double)pdblLongitude 
{ 
    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%f,%f&output=csv",pdblLatitude, pdblLongitude]; 
    NSError* error; 
    NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error]; 
    locationString = [locationString stringByReplacingOccurrencesOfString:@"\"" withString:@""]; 
    return [locationString substringFromIndex:6]; 
} 

Bạn có thể sử dụng chức năng này để lấy địa chỉ từ vĩ độ, kinh độ. Bạn có thể thay đổi theo yêu cầu. Chúng tôi đặt này làm phương thức lớp vì vậy chúng tôi có thể trực tiếp sử dụng nó như

NSString *strAddressFromLatLong = [CLassName getAddressFromLatLon:37.484848 withLongitude:74.48489]; 

EDIT

hãy ngừng sử dụng trên chức năng vì nó đã ngừng làm việc báo cáo trong ý kiến ​​(Không thử nghiệm của tôi). Tôi khuyên bạn nên bắt đầu sử dụng SVGeocoder

+1

một thời gian mã này không làm việc hãy cố gắng tìm thấy một số giải pháp thay thế – btmanikandan

+1

Không làm việc cho tôi Tôi đang sử dụng http://maps.google.com/maps/geo?q=37.785834,-122.406417&output=csv Đầu ra là "610,0,0,0" –

+0

@HardikShah Bạn nhận được kết quả này vì bạn đang sử dụng ** csv **. Thay đổi nó thành ** xml ** hoặc ** json ** như 'output = xml', nó sẽ cho bạn biết rằng đây là mã hóa địa lý cũ và mới là khác nhau. Bạn cũng sẽ nhận được liên kết mã hóa địa lý mới trong phản hồi xml hoặc json. – TheTiger

5
//Place below parser code where you are reading latlng and place your latlng in the url 
NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:[NSURL URLWithString:@"http://maps.googleapis.com/maps/api/geocode/xml?latlng=40.714224,-73.961452&sensor=false"]]; 
[parser setDelegate:self]; 
[parser parse]; 

// Below are the delegates which will get you the exact address easyly 
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict 
{  
    if([elementName isEqualToString:@"formatted_address"]){ 
     got = YES; //got is a BOOL 
    } 
} 

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
{ 
    if(got){ 
     NSLog(@"the address is = %@",string); 
    } 
} 

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ 
} 

//what we are doing is using xmlparser to parse the data which we get through the google map api copy above link and use in browser you will see the xml data brought 

Xin lỗi vì hy vọng tiếng anh xấu của tôi nó willhelp bạn

0

tôi thấy đoạn mã này và nó làm việc cho tôi: https://gist.github.com/flyworld/4222448.

Chỉ cần thay đổi placemark.ISOcountryCode thành placemark.locality.

+0

nvm tìm thấy nó trong tài liệu táo .... administrativeArea – jsetting32

1
- (void)reverseGeocode:(CLLocation *)location { 
CLGeocoder *geocoder = [[CLGeocoder alloc] init]; 
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) { 
    NSLog(@"Finding address"); 
    if (error) { 
     NSLog(@"Error %@", error.description); 
    } else { 
     CLPlacemark *placemark = [placemarks lastObject]; 
     self.myAddress.text = [NSString stringWithFormat:@"%@", ABCreateStringWithAddressDictionary(placemark.addressDictionary, NO)]; 
    } 
}]; 
} 
13

Tôi đang sử dụng mã này và nhận được mã ZIP và tên thành phố. Đã sửa đổi phương thức được thêm bởi Janak.

- (void) getAddressFromLatLon:(CLLocation *)bestLocation 
{ 
    NSLog(@"%f %f", bestLocation.coordinate.latitude, bestLocation.coordinate.longitude); 
    CLGeocoder *geocoder = [[CLGeocoder alloc] init] ; 
    [geocoder reverseGeocodeLocation:bestLocation 
        completionHandler:^(NSArray *placemarks, NSError *error) 
    { 
     if (error){ 
      NSLog(@"Geocode failed with error: %@", error); 
      return; 
     } 
     CLPlacemark *placemark = [placemarks objectAtIndex:0]; 
     NSLog(@"placemark.ISOcountryCode %@",placemark.ISOcountryCode); 
     NSLog(@"locality %@",placemark.locality); 
     NSLog(@"postalCode %@",placemark.postalCode); 

    }]; 

} 
3

Hãy thử yêu cầu ở đây bạn sẽ tìm thấy tất cả dữ liệu về vị trí hiện tại, tên phố/thành phố/khu vực, số nhà nhưng yêu cầu của bạn chỉ cần dán.

NSString *urlString = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",pdblLatitude, pdblLongitude]; 
NSError* error; 
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error]; 

NSData *data = [locationString dataUsingEncoding:NSUTF8StringEncoding]; 
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 

NSDictionary *dic = [[json objectForKey:kResults] objectAtIndex:0]; 
NSString *cityName = [[[dic objectForKey:@"address_components"] objectAtIndex:1] objectForKey:@"long_name"]; 
+0

Tôi đang sử dụng giải pháp của bạn, và nó hoạt động hoàn hảo, nhờ .. –

+0

Kiểm tra xem Link: http://maps.googleapis.com/maps/api /geocode/json?latlng=37.332331,-122.031219&sensor=true Nó đang trở về quốc gia ở đó, vì vậy mã không được tổng quát, vui lòng kiểm tra. –

2

Điều này tốt cho tôi.

Tôi đang nhận được vĩ độ và kinh độ bằng cách sử dụng CLLocationManager và hơn tôi đang chuyển tọa độ của tôi vào CLGeocoder.

import @corelocation and for getting city,country #import <AddressBook/AddressBook.h> 
    -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations 
    { 
    CLLocation *location=[locations lastObject]; 
     CLGeocoder *geocoder=[[CLGeocoder alloc]init]; 

     CLLocationCoordinate2D coord; 
     coord.longitude = location.coordinate.longitude; 
     coord.latitude = location.coordinate.latitude; 
     // or a one shot fill 
     coord = [location coordinate]; 
     NSLog(@"longitude value%f", coord.longitude); 
     NSLog(@"latitude value%f", coord.latitude); 
     [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) { 
      CLPlacemark *placemark = placemarks[0]; 
      NSDictionary *addressDictionary = [placemark addressDictionary]; 
      city = addressDictionary[(NSString *)kABPersonAddressCityKey]; 
      stateloc = addressDictionary[(NSString *)kABPersonAddressStateKey]; 
      country = placemark.country; 


      NSLog(@"city%@/state%@/country%@",city,stateloc,country); 
      [self getImagesFromServer:city]; 

     }]; 

     [self stopSignificantChangesUpdates]; 

    } 

- (void)stopSignificantChangesUpdates 
{ 
    [self.locationManager stopUpdatingLocation]; 
    self.locationManager = nil; 
} 
0

tôi cải thiện @Constantin Saulenco answer- kết quả json tuyệt vời trong không phải lúc nào sắp xếp theo cùng một trật tự - vì vậy thành phố không phải lúc nào cũng đồng index - func này sẽ tìm kiếm một trong những quyền. Đã thêm quốc gia.

NSString *urlString = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",location.coordinate.latitude, location.coordinate.longitude]; 
NSError* error; 
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error]; 

NSData *data = [locationString dataUsingEncoding:NSUTF8StringEncoding]; 
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 

NSDictionary *dic = [[json objectForKey:@"results"] objectAtIndex:0]; 
NSArray* arr = [dic objectForKey:@"address_components"]; 
//Iterate each result of address components - find locality and country 
NSString *cityName; 
NSString *countryName; 
for (NSDictionary* d in arr) 
{ 
    NSArray* typesArr = [d objectForKey:@"types"]; 
    NSString* firstType = [typesArr objectAtIndex:0]; 
    if([firstType isEqualToString:@"locality"]) 
     cityName = [d objectForKey:@"long_name"]; 
    if([firstType isEqualToString:@"country"]) 
     countryName = [d objectForKey:@"long_name"]; 

} 

NSString* locationFinal = [NSString stringWithFormat:@"%@,%@",cityName,countryName]; 
7

Nó làm việc cho tôi :)

CLGeocoder *ceo = [[CLGeocoder alloc]init]; 
CLLocation *loc = [[CLLocation alloc]initWithLatitude:26.93611 longitude:26.93611]; 

[ceo reverseGeocodeLocation: loc completionHandler: 
^(NSArray *placemarks, NSError *error) { 
    CLPlacemark *placemark = [placemarks objectAtIndex:0]; 
    NSLog(@"placemark %@",placemark); 
    //String to hold address 
    NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "]; 
    NSLog(@"addressDictionary %@", placemark.addressDictionary); 

    NSLog(@"placemark %@",placemark.region); 
    NSLog(@"placemark %@",placemark.country); // Give Country Name 
    NSLog(@"placemark %@",placemark.locality); // Extract the city name 
    NSLog(@"location %@",placemark.name); 
    NSLog(@"location %@",placemark.ocean); 
    NSLog(@"location %@",placemark.postalCode); 
    NSLog(@"location %@",placemark.subLocality); 

    NSLog(@"location %@",placemark.location); 
    //Print the location to console 
    NSLog(@"I am currently at %@",locatedAt); 
}]; 
0

Vui lòng kiểm tra chức năng dưới đây

func getDataCity(tmpLat:Double,tmpLong:Double) { 

    let tmpCLGeocoder = CLGeocoder.init() 
    if tmpLat > 0 , tmpLong > 0 
    { 
     let tmpDataLoc = CLLocation.init(latitude: tmpLat, longitude: tmpLong) 

     tmpCLGeocoder.reverseGeocodeLocation(tmpDataLoc, completionHandler: {(placemarks,error) in 

      guard let tmpPlacemarks = placemarks else{ 
       return 
      } 
      let placeMark = tmpPlacemarks[0] as CLPlacemark 

      guard let strLocality = placeMark.locality else{ 
       return 
      } 
      // strLocality is your city 
      guard let strSubLocality = placeMark.subLocality else{ 

       return 
      } 
      // strSubLocality is your are of city 
     }) 
    } 
} 
Các vấn đề liên quan