2014-09-16 2 views
1

У меня есть ответ Json. Вот оно:Разбор Json на Картах Google iOS

Directions { 
routes =  (
      { 
     bounds =    { 
      northeast =     { 
       lat = "39.893397"; 
       lng = "42.2477961"; 
      }; 
      southwest =     { 
       lat = "21.4204199"; 
       lng = "39.2398944"; 
      }; 
     }; 
     copyrights = "Map data \U00a92014 Google, Mapa GISrael, ORION-ME"; 
     legs =    (
          { 
       distance =      { 
        text = "2,940 km"; 
        value = 2940341; 
       }; 
       duration =      { 
        text = "1 day 15 hours"; 
        value = 138793; 
       }; 
       "end_address" = "Unnamed Road, Erzincan Province, Turkey"; 
       "end_location" =      { 
        lat = "39.893397"; 
        lng = "39.906191"; 
       }; 
       "start_address" = "4289, Al Hajlah, Mecca 24231\U00a06970, Saudi Arabia"; 
       "start_location" =      { 
        lat = "21.4204199"; 
        lng = "39.8258119"; 
       }; 
       steps =      (
              { 
         distance =        { 
          text = "0.6 km"; 
          value = 630; 
         }; 
         duration =        { 
          text = "1 min"; 
          value = 55; 
         }; 
         "end_location" =        { 
          lat = "21.4235672"; 
          lng = "39.8211613"; 
         }; 
         "html_instructions" = "Head <b>west</b> on <b>Alsouq Alsagheer Tunnel</b>"; 
         polyline =        { 
          points = "[email protected][email protected][email protected]@[email protected]@[email protected]@[email protected]@Y`@CD[[email protected]@[email protected]@[email protected]]N[[email protected]]ROJ"; 
         }; 
         "start_location" =        { 
          lat = "21.4204199"; 
          lng = "39.8258119"; 
         }; 
         "travel_mode" = DRIVING; 

и это продолжается ....

Вот код из моего проекта:

Direction.h

-(void)retrieveDirectionsFromOrigin:(CLLocationCoordinate2D)origin toDestination:(CLLocationCoordinate2D)destination 
{ 
NSString *directionsURL=[NSString stringWithFormat:@"http://maps.google.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=false",origin.latitude,origin.longitude,destination.longitude,destination.longitude]; 
_directionsURL=[NSURL URLWithString:directionsURL]; 
[self retrieveDirections:nil withDelegate:self]; 
} 
-(void)retrieveDirections:(SEL)selector withDelegate:(id)delegate{ 
dispatch_async(dispatch_get_main_queue(), ^{ 
    NSData *data = [NSData dataWithContentsOfURL:_directionsURL]; 
    [self fetchedData:data withDelegate:delegate]; 
}); 
} 

-(void)fetchedData:(NSData *)data withDelegate:(id)delegate{ 
NSError* error; 
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
NSLog(@"Directions %@",json); 
if(!error){ 
    self.steps = json[@"routes"][0][@"legs"][0][@"steps"]; 
} 

//MapViewController.m

marker.position = CLLocationCoordinate2DMake(21.422492, 39.826169); 
marker2.position = CLLocationCoordinate2DMake(21.413333, 39.893333); 
marker.map = mapView; 
marker2.map = mapView; 

directions=[[Directions alloc]init]; 
[directions retrieveDirectionsFromOrigin:marker.position toDestination:marker2.position]; 
[mapViewView setNeedsDisplay]; 
[mapView setNeedsDisplay]; 
[self.view bringSubviewToFront:backButton]; 

}

Я новичок. Пожалуйста, дайте мне знать, что делать дальше, показывая маршруты через полилинию. Благодаря

+0

не испытывайте 'е rror' из NSJSONSerialization (или любой другой API, у которого есть 'error' parm). Проверьте результат, и если это nil, тогда выведите «error», чтобы отобразить причину сбоя. –

+0

Иначе дело в следующем - подумать над вопросом. –

ответ

1

Вот подсказка о том, как создать полилинию, которая поможет вам начать на вашем пути

Собирают polystrings из шагов

NSArray *steps = [valDictionary valueForKey:@"steps"]; 
    for (NSDictionary *stepdic in steps) { 
     NSString *polyStr = [[stepdic valueForKey:@"polyline"] valueForKey:@"points"]; 
     if (polyStr != nil) [polyStrings addObject:polyStr]; 
    } 

Создать единый путь от polystrings для гладкой линии и создать окончательную полилинию

GMSMutablePath *path = [GMSMutablePath path]; 
    for (NSString *polyStr in polyStrings) { 
      GMSPath *p = [GMSPath pathFromEncodedPath:polyStr]; 
      for (NSUInteger i=0; i < p.count; i++) { 
       [path addCoordinate:[p coordinateAtIndex:i]]; 
      } 
    } 

    GMSPolyline *polyLint = [GMSPolyline polylineWithPath:path]; 

удачи

+0

Вы писали: «if (polyStr! = Nil) [polyStrings addObject: polyStr];" Что такое polyStrings в этом коде? Пожалуйста, объясни. – Hasam

+0

любезно дайте мне знать! – Hasam

+0

polyStrings - это всего лишь NSMutableArray из polyString, взятый из steps.polyline.points –

Смежные вопросы