2025-02-10

    在iOS 5 中蘋果公司取消瞭地理逆向編碼的功能,我的畢業設計要用到這個功能,我查瞭一下這方面的代碼,有兩個比較好的開源類庫可以實現這個功能,但是到頭來還是調用GoogleMap API來實現的。

        這兩個開源類庫都可以很好的實現功能,但是出於學習的目的,我還是自己寫瞭一個調用GoogleMap API和JSON解析的代碼。

    1、首先引入JSON-framework和ASIHTTPRequest的相關代碼

    2、下面是實現代碼

  

[plain] 
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:@"https://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將我需要的那部分字符串直接截取出來瞭。

   

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *