iOS通过经纬度反向解析地址


1. 在工程里面引入CoreLocation.framework和MapKit.framework。

2. 在.h文件里面加入如下代码:

  1. #import <CoreLocation/CoreLocation.h>   
  2. #import <MapKit/MKReverseGeocoder.h>   
  3. #import <MapKit/MKPlacemark.h>  
  1. @interface RootViewController : UICustomViewController<CLLocationManagerDelegate, MKReverseGeocoderDelegate> {  
  2.     CLLocationManager *gps;  
  3. }  

3. 在.m文件中加入以下代码:

  1. - (void)locationManager:(CLLocationManager *)locationManager didUpdateToLocation:(CLLocation *)newLocation  
  2.            fromLocation:(CLLocation *) oldLocation;  
  3. {  
  4.     self.location = [NSString stringWithFormat:@"%f,%f",newLocation.coordinate.latitude, newLocation.coordinate.longitude];  
  5.     [self startedReverseGeoderWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];  
  6. }  
  7.   
  8. - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {  
  9.     if ( [error code] == kCLErrorDenied ) {  
  10.         [manager stopUpdatingHeading];  
  11.     } else if ([error code] == kCLErrorHeadingFailure) {  
  12.           
  13.     }  
  14. }  
  15.   
  16. -(void) startedReverseGeoderWithLatitude:(double)latitude longitude:(double)longitude{  
  17.     CLLocationCoordinate2D coordinate2D;  
  18.     coordinate2D.longitude = longitude;  
  19.     coordinate2D.latitude = latitude;  
  20.     MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:coordinate2D];  
  21.     geoCoder.delegate = self;  
  22.     [geoCoder start];  
  23. }  
  24.   
  25. -(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark  
  26. {  
  27.       
  28.     NSString *subthroung=placemark.thoroughfare;  
  29.     NSString *local=placemark.locality;  
  30.     self.textFieldName.text = [NSString stringWithFormat:@"您当前所在位置:%@,%@",local, subthroung];  
  31.       
  32. }  
  33. -(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error  
  34. {  
  35. }  

 
  1. - (void)viewDidLoad {  
  2.     [super viewDidLoad];  
  3.       
  4.     gps = [[CLLocationManager alloc] init];  
  5.     gps.delegate = self;  
  6.     gps.desiredAccuracy = kCLLocationAccuracyBest;  
  7.     gps.distanceFilter = kCLDistanceFilterNone;  
  8.     [gps startUpdatingLocation];  
  9. }  

编译运行下就能看到结果了,哈哈~

相关内容