2013-04-12 39 views
2

我有這樣的:的Objective-C + JSON解析objectForKey爲谷歌Places API的

//request stuff 
NSString *searchString = [NSString stringWithFormat:@"Sydney"]; 
NSString *urlString = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/textsearch/json?query=%@&sensor=true&key=mykeynotyours!",searchString]; 

NSURL *requestURL = [NSURL URLWithString:urlString]; 
NSURLRequest *request = [NSURLRequest requestWithURL:(requestURL)]; 

//response 
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
NSError *jsonParsingError = nil; 
NSDictionary *locationResults = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError]; 

NSLog(@"%@",locationResults); 

這是吐出了幾個結果,其中第一個就是我想要的,但我不能說獲得緯度和經度像我可以與其他的API:

NSString *stringLatitude = [locationResults objectForKey:@"lat"]; 

我懷疑它在尋找關鍵的是「結果」的一個子集關鍵,我不知道如何告訴它:-(

結果:

2013-04-12 18:47:49.784 Test[26984:c07] { 
"html_attributions" =  (
); 
results =  (
      { 
     "formatted_address" = "Sydney NSW, Australia"; 
     geometry =    { 
      location =     { 
       lat = "-33.8674869"; 
       lng = "151.2069902"; 
      }; 
      viewport =     { 
       northeast =      { 
        lat = "-33.4245981"; 
        lng = "151.3426361"; 
       }; 
       southwest =      { 
        lat = "-34.1692489"; 
        lng = "150.502229"; 
       }; 
      }; 
     }; 

感謝任何指導!

回答

5

您可以使用訪問幾何lat和郎下面的代碼

NSString *stringLatitude = [[[[[locationResults objectForKey:@"results"] objectAtIndex:0] objectForKey:@"geometry"] objectForKey:@"location"] valueForKey:@"lat"]; 
NSString *stringLongitude = [[[[[locationResults objectForKey:@"results"] objectAtIndex:0] objectForKey:@"geometry"] objectForKey:@"location"] valueForKey:@"lng"]; 
+0

這看起來很有希望,但不起作用... – NessyString

+0

它應該工作,但讓我再檢查是否有任何錯誤..! –

+0

它在NSDictionary上拋出一個沒有索引值的錯誤(locationResults是一個NSDictionary對象) – NessyString

0

使用本

NSString *stringLatitude = [[[[[locationResults objectForKey:@"results" ]objectAtIndex:0] objectForKey:@"geometry"] objectForKey:@"location"] objectForKey:@"lat"]; 
NSString *stringLongitude = [[[[[locationResults objectForKey:@"results" ]objectAtIndex:0] objectForKey:@"geometry"] objectForKey:@"location"] objectForKey:@"lng"]; 
0

使用的是iOS 7?這拖放到你的項目:https://github.com/gdyer/GDGooglePlaces

然後...只是使用- (id)initWithPlaceCategory:(NSString *)_category urlStub:(NSString *)_stub lat:(float)\ _lat andLon:(float)_lon;

測繪,分析,查看,方向,分享,更多的是爲大家處理。