iPhone开发笔记(13)调用GoogleMap API实现地理逆向编码

来源:互联网 发布:qt wifi windows 编辑:程序博客网 时间:2024/05/22 18:23

    在iOS 5 中苹果公司取消了地理逆向编码的功能,我的毕业设计要用到这个功能,我查了一下这方面的代码,有两个比较好的开源类库可以实现这个功能,但是到头来还是调用GoogleMap API来实现的。

    https://github.com/mjisrawi/iOS-Geocoding-Services

    https://github.com/samvermette/SVGeocoder

    这两个开源类库都可以很好的实现功能,但是出于学习的目的,我还是自己写了一个调用GoogleMap API和JSON解析的代码。

    1、首先引入JSON-framework和ASIHTTPRequest的相关代码

    2、下面是实现代码

   

self.locationManager = [[CLLocationManager alloc] init];//创建位置管理器    self.locationManager.delegate=self;//设置代理    self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;//指定需要的精度级别    self.locationManager.distanceFilter=1000.0f;//设置距离筛选器    [self.locationManager startUpdatingLocation];//启动位置管理器            NSString *str = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=true®ion=zh&language=zh-CN",[[locationManager location] coordinate].latitude,[[locationManager location] coordinate].longitude];        NSURL *url = [NSURL URLWithString:str];    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];    [request startSynchronous];    NSString *response = [request responseString];    NSLog(@"%@",response);    NSString *strrrr = [response stringByReplacingOccurrencesOfString:@"\n" withString:@""];    NSString *straaa = [strrrr stringByReplacingOccurrencesOfString:@" " withString:@""];    NSRange range = NSMakeRange(11, [straaa length]-26);    NSString *strbbb = [straaa substringWithRange:range];    NSMutableArray *dictionary = [strbbb JSONValue];    self.addressStr = [[dictionary objectAtIndex:0] objectForKey:@"formatted_address"];

   

 3、这里需要说明的是GoogleMap API返回的JSON字符串含有很多空格和换行符号,这种情况导致进行JSON解析的时候出现错误,所以需要对返回的字符串进行处理,替换掉里面的空格和换行。因为这个字符串很复杂,我最后干脆直接用NSRange将我需要的那部分字符串直接截取出来了。


    

    

原创粉丝点击