2013-10-28 122 views
1

我用代碼來解析從谷歌API方向的座標和折線:如何在iPhone中解析谷歌方向API數據從谷歌地圖?

-(void)routeParser:(NSString *)sourceAddress andDestination:(NSString *)destinationAddress{ 
    NSLog(@"des sour %@",sourceAddress); 
    NSError *error = nil; 

    NSString* apiUrlStr = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=false", sourceAddress, destinationAddress]; 
    //&alternatives=true 
    NSURL* apiUrl = [NSURL URLWithString:apiUrlStr]; 
    NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&error]; 
    NSLog(@"apiResponse %@",apiResponse); 
    SBJsonParser *jsonParser = [SBJsonParser new]; 
    NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:apiResponse]; 
    NSLog(@"apiResponse is : %@",[jsonData objectForKey:@"routes"]); 
    NSArray *routeArray = [[NSArray alloc]init]; 
    routeArray= [jsonData objectForKey:@"routes"]; 

    for(int i=0;i<[routeArray count];i++) 
    { 
     NSDictionary *tempDictionary = [routeArray objectAtIndex:i]; 
     if([tempDictionary objectForKey:@"overview_polyline"]!=nil) 
     { 
      NSDictionary *secTempDictionary = [tempDictionary objectForKey:@"overview_polyline"]; 
      if([secTempDictionary objectForKey:@"points"]!=nil) 
      { 
       NSString * routePoint =[secTempDictionary objectForKey:@"points"]; 

       [routeSetAry addObject:routePoint]; 

       encodedPoints = [secTempDictionary objectForKey:@"points"]; 
      } 
      // NSLog(@"secTempDictionary is: %@", secTempDictionary); 
     } 
     if([tempDictionary objectForKey:@"legs"]!=nil) 
     { 
      NSArray *lagArray = [[NSArray alloc]init]; 
      lagArray= [tempDictionary objectForKey:@"legs"]; 

      for(int i=0;i<[lagArray count];i++) 
      { 
       NSDictionary *thirdTempDictionary = [lagArray objectAtIndex:i]; 
       if([thirdTempDictionary objectForKey:@"steps"]!=nil) 
       { 
        NSArray *stepsArray = [[NSArray alloc]init]; 
        stepsArray= [thirdTempDictionary objectForKey:@"steps"]; 

        for(int i=0;i<[stepsArray count];i++) 
        { 
         NSDictionary *forthTempDictionary = [stepsArray objectAtIndex:i]; 

         if([forthTempDictionary objectForKey:@"html_instructions"]!=nil) 
         { 
          NSString * directionStr =[forthTempDictionary objectForKey:@"html_instructions"]; 

          NSRange range; 
          while ((range = [directionStr rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound){ 
           directionStr=[directionStr stringByReplacingCharactersInRange:range withString:@""]; 
          } 
          [directionStrAry addObject:directionStr]; 
         } 

         NSDictionary *fifthTempDictionary = [forthTempDictionary objectForKey:@"polyline"]; 
         if([fifthTempDictionary objectForKey:@"points"]!=nil) 
         { 
          NSString * routePoint =[fifthTempDictionary objectForKey:@"points"]; 

          [polylineSetAry addObject:routePoint]; 

          // encodedPoints = [fifthTempDictionary objectForKey:@"points"]; 
         } 
         NSDictionary *sixthTempDictionary =[forthTempDictionary objectForKey:@"distance"]; 
         if([sixthTempDictionary objectForKey:@"text"]!=nil) 
         { 
          NSString * distanceStr =[sixthTempDictionary objectForKey:@"text"]; 

          [distanceStrAry addObject:distanceStr]; 

          // encodedPoints = [fifthTempDictionary objectForKey:@"points"]; 
         } 
        } 
       } 
      } 
     } 
    } 

    NSLog(@"routeSetAry is :%@",routeSetAry); 
    NSLog(@"polylineSetAry is : %i",polylineSetAry.count); 

} 

,但問題是它記錄空,並在開始返回null apiResponse。我無法理解我的錯在哪裏,有人幫忙?

+0

請使用最新的谷歌API version.I認爲你正在使用舊的API網址。 – Suresh

+0

在瀏覽器此url返回json,所以我認爲這不是backdated – Reyjohn

+0

任何一個可以幫助PLZ?我卡在這裏:( – Reyjohn

回答

-1

Google拒絕通過客戶端腳本訪問。您需要處理該服務器端以下載json數據並將json結果傳遞給客戶端。

更新:

串產地= 「奈,印度泰米爾納德邦」; string Destination =「班加羅爾,卡納塔克邦,印度」;

  var geojsonurl = "http://maps.googleapis.com/maps/api/directions/json?origin=" + Origin + "&destination=" + Destination + " &sensor=true"; 

      WebClient c = new WebClient(); 
      var json = c.DownloadString(geojsonurl); 
      GoogleMapsRoutes data = JsonConvert.DeserializeObject<GoogleMapsRoutes>(json); 

      StringBuilder Originstrlatlng = new StringBuilder(); 
      StringBuilder Deststrlatlng = new StringBuilder(); 

      if (!(data == null)) 
      { 
       foreach (var item in data.routes[0].legs[0].steps) 
      { 
       Originstrlatlng.Append (item.start_location.lat.ToString() + "," + item.start_location.lng.ToString() + "|"); 
       Deststrlatlng.Append(item.end_location.lat.ToString() + "," + item.end_location.lng.ToString() + "|"); 
      } 
      } 


public class GoogleMapsRoutes 
{ 
    public List<Route> routes { get; set; } 
    public string status { get; set; } 

} 

public class Northeast 
{ 
    public double lat { get; set; } 
    public double lng { get; set; } 
} 

public class Southwest 
{ 
    public double lat { get; set; } 
    public double lng { get; set; } 
} 

public class Bounds 
{ 
    public Northeast northeast { get; set; } 
    public Southwest southwest { get; set; } 
} 

public class Distance 
{ 
    public string text { get; set; } 
    public int value { get; set; } 
} 

public class Duration 
{ 
    public string text { get; set; } 
    public int value { get; set; } 
} 

public class EndLocation 
{ 
    public double lat { get; set; } 
    public double lng { get; set; } 
} 

public class StartLocation 
{ 
    public double lat { get; set; } 
    public double lng { get; set; } 
} 

public class Distance2 
{ 
    public string text { get; set; } 
    public int value { get; set; } 
} 

public class Duration2 
{ 
    public string text { get; set; } 
    public int value { get; set; } 
} 

public class EndLocation2 
{ 
    public double lat { get; set; } 
    public double lng { get; set; } 
} 

public class Polyline 
{ 
    public string points { get; set; } 
} 

public class StartLocation2 
{ 
    public double lat { get; set; } 
    public double lng { get; set; } 
} 

public class Step 
{ 
    public Distance2 distance { get; set; } 
    public Duration2 duration { get; set; } 
    public EndLocation2 end_location { get; set; } 
    public string html_instructions { get; set; } 
    public Polyline polyline { get; set; } 
    public StartLocation2 start_location { get; set; } 
    public string travel_mode { get; set; } 
    public string maneuver { get; set; } 
} 

public class Leg 
{ 
    public Distance distance { get; set; } 
    public Duration duration { get; set; } 
    public string end_address { get; set; } 
    public EndLocation end_location { get; set; } 
    public string start_address { get; set; } 
    public StartLocation start_location { get; set; } 
    public List<Step> steps { get; set; } 
    public List<object> via_waypoint { get; set; } 
} 

public class OverviewPolyline 
{ 
    public string points { get; set; } 
} 

public class Route 
{ 
    public Bounds bounds { get; set; } 
    public string copyrights { get; set; } 
    public List<Leg> legs { get; set; } 
    public OverviewPolyline overview_polyline { get; set; } 
    public string summary { get; set; } 
    public List<object> warnings { get; set; } 
    public List<object> waypoint_order { get; set; } 
} 

This works。你試一試。

+0

這個答案用另一種語言,不是iOS相關的。 – Isuru

0
- (void) getRoute 
{ 
    polyline.map = nil; 
    [googleMapView clear]; 
    NSString *strUrl = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/directions/json?&alternatives=true&origin=%@&destination=%@&key=%@&sensor=false",self.sourceText.text,self.destnText.text,googleAPI_Key]; 

    [self routeDataUrl1:strUrl]; 
    [self.view addSubview:self.getInfo]; 
    [self.view addSubview:customIndicatorView]; 
} 

-(void) connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    if (webData) //webData is object of NSData 
    { 
     [self gettingData:webData ]; //calling the method gettingData 
    } 

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
    webData=nil; 
} 

//after that gettingData method 

- (void) gettingData:(NSData *)data 
{ 

    NSDictionary *allDataDictionary = [NSJSONSerialization 
            JSONObjectWithData:data options:0 
            error:nil]; 

    if ([[NSString stringWithFormat:@"%@",[allDataDictionary objectForKey 
    : @"status"]] isEqualToString: @"OK"]) 

    { 

     collectionArray =[[NSMutableArray alloc]init]; 
     NSMutableArray *legsArray = [[NSMutableArray alloc] initWithArray:allDataDictionary[@"routes"]]; 


     for (int i=0; i< [legsArray count]; i++) 
     { 

      [collectionArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:legsArray[i][@"legs"][0][@"distance"][@"text"],@"Distance", legsArray[i][@"legs"][0][@"duration"][@"text"],@"Duration",legsArray [i][@"summary"],@"Address",legsArray[i][@"legs"][0][@"summary"][@"html_instructions"][@"text"],@"HtmlInstructions",legsArray[i][@"overview_polyline"][@"points"],@"OverviewPolyline", nil]]; 
      [polyLineArray addObject:legsArray[i][@"legs"][0][@"steps"]]; 
      NSLog(@"11 == %@",legsArray[i][@"legs"][0][@"steps"]);   
     }  
     [self.getInfo reloadData]; //where getInfo is the TableView 
    } 
    else 
    { 
     NSString *msg=[allDataDictionary objectForKey:@"error_message"]; 
     UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error !" message:msg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 

     [alert show]; 
    } 
} 

希望這可以幫助你......