IOS获取当前地理位置文本

以下内容摘抄自网络,著作权属于原作者
http://blog.csdn.net/lvxiangan/article/details/26015147

方法1:使用ios自带联网查询功能,断网会报 PBRequester failed with Error Error Domain=NSURLErrorDomain Code=-1009 "似乎已断开与互联网的连接。" UserInfo=0x1e2ea840 {NSErrorFailingURLStringKey=https://gsp4-cn.ls.apple.com/PlaceSearchServlet, NSErrorFailingURLKey=https://gsp4-cn.ls.apple.com/PlaceSearchServlet, NSLocalizedDescription=似乎已断开与互联网的连接。, NSUnderlyingError=0x1e1172c0 "似乎已断开与互联网的连接。"}

发现之前的地图获取当前地理位置信息在Deprecated in iOS 5.0。已经被苹果弃之不用了。推荐
使用CLGeocoder来替代。发现非常简单,比之前写的方法简单了不少。
地图的前提是你导入了MapKit这个库
 
#import <MapKit/MKMapView.h>
先声明一个全局的CLLocationManager对象。  
    CLLocationManager *_currentLoaction;
之后开启定位功能。
    _currentLoaction = [[CLLocationManager alloc] init];
    _currentLoaction.delegate = self;
    [_currentLoaction startUpdatingLocation];
 
定位结束之后更新当前的地址经纬度等信息。
#pragma mark - Location 
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"locError:%@", error);
    
}


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    [_currentLoaction stopUpdatingLocation];
    
    NSString *strLat = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.latitude];
    NSString *strLng = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.longitude];
    NSLog(@"Lat: %@  Lng: %@", strLat, strLng);
    
    [_geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        _placeMark = [placemarks objectAtIndex:0];
        _locationLabel.text = _placeMark.administrativeArea;
        ITTDINFO(@"%@",_locationLabel.text);
        // we have received our current location, so enable the "Get Current Address" button
    }];
}


我稍微解释一下
 
_geocoder 这个是我先要声明的CLGeocoder。使用之前要alloc,才能使用。
我刚开始犯了一个低级错误,没有在viewDidLoad方法中_geocoder = [[CLGeocoder alloc] init];导致一直nil无法出现block的方法。非常简单吧哈哈。

获取当前所在地的地理位置信息需要使用一个新的类,MKReverseGeocoder。这个类在MapKit.framework中。我们把框架加进来,并将头文件导入就可以用了。

敲了一会代码,结果发现这个类iOS5.0就不用了。真是的。为了照顾兼容性,我们先研究MKReverseGeocoder,等下再来研究这个新类,恩,名字叫做CLGeocoder,恩,没拼错。在CoreLocation里面。

先说MKReverseGeocoder的用法。(忍不住出来吐个槽,一般看见被划掉的红线,一边敲回车,还真是说不出来的违和啊。)

。。。。。。。。。。。。。。。

表示测试完成了,IOS的网络总是假死,一假死,各种需要使用网络的的功能,就不怎好用了。桑心。

 

MKReverseGeocoder的初始化,很简单。

 

MKReverseGeocoder *geocoder = [[MKReverseGeocoder allocinitWithCoordinate:currentCoordinate2D];

      geocoder.delegate = self;

[geocoder start];

调用以上代码后呢,会自动调用反向地址编码的API。我们这边使用代理来接收。至于代理方法么,我们要实现两个。

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {

}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error{

}

第一个方法是获取反向编码的。第二个是当反向编码失败时,处理错误使用的。

我们主要讨论第一个方法。

placemarkMKPlacemark类的对象)其实是geocoderMKReverseGeocoder类的对象)的一个属性。从geocoder里面取placemark这个和直接取placemark这个其实区别不大。而我们需要的信息主要就在这个里面了。

// 这个字典存放基础数据

@property (nonatomicreadonlyNSDictionary *addressDictionary;

让我们试试看,能从这个字典里面倒出来些什么东西。

以下是我用这个addressDictionary属性倒出来的字典。我们分析看看。

{

    City = "\U897f\U5b89\U5e02";// 城市名字

    Country = "\U4e2d\U56fd";// 国家名字

    CountryCode = CN;// 国家编码

    FormattedAddressLines =     (

        "\U4e2d\U56fd",

        "\U9655\U897f\U7701\U897f\U5b89\U5e02\U96c1\U5854\U533a",

        "\U9ad8\U65b0\U516d\U8def34\U53f7"

    ); // 这个应该是格式化后的地址了

    State = "\U9655\U897f\U7701"; // 

    Street = "\U9ad8\U65b0\U516d\U8def 34\U53f7";// 街道完整名称

    SubLocality = "\U96c1\U5854\U533a";//区名

    SubThoroughfare = "34\U53f7";//具体地址

    Thoroughfare = "\U9ad8\U65b0\U516d\U8def";//街道名称

}

 

注意:上面的这个字典是可以直接转化为联系人的字典的,通过这个ABCreateStringWithAddressDictionary属性。

 

以下是placemark的其他属性。大家可以随意取用。

// address dictionary properties

@property (nonatomicreadonlyNSString *name; // eg. Apple Inc.

@property (nonatomicreadonlyNSString *thoroughfare; // street address, eg. 1 Infinite Loop

@property (nonatomicreadonlyNSString *subThoroughfare; // eg. 1

@property (nonatomicreadonlyNSString *locality; // city, eg. Cupertino

@property (nonatomicreadonlyNSString *subLocality; // neighborhood, common name, eg. Mission District

@property (nonatomicreadonlyNSString *administrativeArea; // state, eg. CA

@property (nonatomicreadonlyNSString *subAdministrativeArea; // county, eg. Santa Clara

@property (nonatomicreadonlyNSString *postalCode; // zip code, eg. 95014

@property (nonatomicreadonlyNSString *ISOcountryCode; // eg. US

@property (nonatomicreadonlyNSString *country; // eg. United States

@property (nonatomicreadonlyNSString *inlandWater; // eg. Lake Tahoe

@property (nonatomicreadonlyNSString *ocean; // eg. Pacific Ocean

@property (nonatomicreadonlyNSArray *areasOfInterest; // eg. Golden Gate Park

 

注意:我在使用的过程中发现,如果网络假死,则有可能较长时间无法获得逆向的结果。这一点可能需要大家注意。

哎呀呀呀,差点忘了,IOS5下不推荐使用我上面讲的一大堆。我们需要用这个CLGeocoder类。

使用方法也很简单。参照如下步骤:

首先创建一个CLGeocoder对象,然后调用他的- (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler;方法。按照需要的参数类型传参。有的筒子会问这个CLGeocodeCompletionHandler东西怎么写?这个其实是IOS4之后就被官方大力推荐使用的BLOCK,不会用的同学快去看文档吧。

CLGeocodeCompletionHandler的定义就是这样的。typedef void(^CLGeocodeCompletionHandler)(NSArray *placemarks, NSError *error); 我们只要写好一个block对象传进去就好了。

 

以下是使用CLGeocoder的参考代码。不用代理了是不是很开心呢?

    CLGeocoder* geocoder = [[CLGeocoder alloc] init];

   

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

         NSLog(@"%@",placemarks);

     }];


方法2: 利用google地图api

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //根据经纬度 查找地址  
  2.   
  3. - (void)getAddress:(NSString *)aLongitude withLatitude:(NSString *)aLatitude withBlock:(void(^)(id result))callback {  
  4.   
  5.     callbackBlock = callback;  
  6.   
  7.     NSString *url = @"http://maps.googleapis.com/maps/api/geocode/json";  
  8.   
  9.     NSString *coordinateStr = [NSString stringWithFormat:@"%@,%@",aLatitude,aLongitude];  
  10.   
  11.     NSMutableDictionary *params = [[NSMutableDictionary alloc] init];  
  12.   
  13.     [params setValue:@"true" forKey:@"sensor"];  
  14.   
  15.     [params setValue:@"cn" forKey:@"language"];  
  16.   
  17.     [params setObject:coordinateStr forKey:@"latlng"];  
  18.   
  19.     NSString *tempParamStr = [self addParametersToRequest:params];  
  20.   
  21.     NSString *tempUrl = [NSString stringWithFormat:@"%@?%@",url,tempParamStr];  
  22.   
  23.     NSMutableURLRequest *operationRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:tempUrl]];  
  24.   
  25.     NSURLConnection *operationConnection = [[NSURLConnection alloc] initWithRequest:operationRequest delegate:self startImmediately:NO];  
  26.   
  27.     [operationConnection start];  
  28.   
  29. }  
  30.   
  31.   
  32.   
  33. - (NSString *)addParametersToRequest:(NSMutableDictionary*)parameters {  
  34.   
  35.     NSMutableArray *paramStringsArray = [NSMutableArray arrayWithCapacity:[[parameters allKeys] count]];  
  36.   
  37.     for(NSString *key in [parameters allKeys]) {  
  38.   
  39.         NSObject *paramValue = [parameters valueForKey:key];  
  40.   
  41.         if ([paramValue isKindOfClass:[NSString class]]) {  
  42.   
  43.             [paramStringsArray addObject:[NSString stringWithFormat:@"%@=%@", key, [(NSString *)paramValue encodedURLParameterString]]];  
  44.   
  45.         } else {  
  46.   
  47.             [paramStringsArray addObject:[NSString stringWithFormat:@"%@=%@", key, paramValue]];  
  48.   
  49.         }  
  50.   
  51.     }  
  52.   
  53.     NSString *paramsString = [paramStringsArray componentsJoinedByString:@"&"];  
  54.   
  55.     return paramsString;  
  56.   
  57. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值