iPhone開發筆記(13)調用GoogleMap API實現地理逆向編碼

    在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將我需要的那部分字符串直接截取出來了。


    

    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章