我正在使用 Google Directions iOS API。我正在使用 JSON 而不是 XML 获取数据。但我AFNetworking
习惯于为我简化这一点。AFNetworking
可在 github 上找到。现在,我可以在MKMapView
. 这是我的代码:
// AFNETWORKING ==========================================================
AFHTTPClient *_httpClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://maps.googleapis.com/"]];
[_httpClient registerHTTPOperationClass: [AFJSONRequestOperation class]];
[_httpClient setDefaultHeader:@"Accept" value:@"application/json"];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setObject:[NSString stringWithFormat:@"%f,%f", location.coordinate.latitude, location.coordinate.longitude] forKey:@"origin"];
[parameters setObject:[NSString stringWithFormat:@"%f,%f", location2.coordinate.latitude, location2.coordinate.longitude] forKey:@"destination"];
[parameters setObject:@"false" forKey:@"sensor"];
[parameters setObject:@"driving" forKey:@"mode"];
[parameters setObject:@"metric" forKey: @"units"];
NSMutableURLRequest *request = [_httpClient requestWithMethod:@"GET" path: @"maps/api/directions/json" parameters:parameters];
request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
AFHTTPRequestOperation *operation = [_httpClient HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSInteger statusCode = operation.response.statusCode;
if (statusCode == 200) {
[self parseResponse:responseObject];
} else {
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { }];
[_httpClient enqueueHTTPRequestOperation:operation];
// ROUTE SETUP AND RESPONSE RECIEVED METHOD ==========================================================
- (void)parseResponse:(NSDictionary *)response {
NSArray *routes = [response objectForKey:@"routes"];
NSDictionary *routePath = [routes lastObject];
if (routePath) {
NSString *overviewPolyline = [[routePath objectForKey: @"overview_polyline"] objectForKey:@"points"];
NSLog(@"Status: %@", [response objectForKey: @"status"]);
NSLog(@"Legs: %@", [routePath objectForKey: @"legs[]"]);
_path = [self decodePolyLine:overviewPolyline];
NSInteger numberOfSteps = _path.count;
CLLocationCoordinate2D coordinates[numberOfSteps];
for (NSInteger index = 0; index < numberOfSteps; index++) {
CLLocation *location = [_path objectAtIndex:index];
CLLocationCoordinate2D coordinate = location.coordinate;
coordinates[index] = coordinate;
}
polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
[self.mapView addOverlay:polyLine];
}
}
这是使路由正常运行的主要代码。而且效果很好!但现在我要做的是获取方向列表和完整的持续时间和摘要。因此,我深入研究了Google Directions API 文档,它告诉我使用其不同的字典、数组和对象。但我没有运气。我的状态为 OK。当我记录routes
数组的计数时,它只有一个对象。然后最重要的是,legs[]
数组是NULL
.
NSLog(@"Legs is: %@", [routePath objectForKey: @"legs[]"]);
输出:
腿是(空)
Legs[]
包括所有重要的内容,例如方向列表和持续时间。Summary
不是NULL
,它给出了路线绕过的街道之一的名称。我不知道那是一个总结。可能是因为routes
数组中只有一个对象。waypoint_order
也是。warnings[]
_ 当然是有效的,这就是我让路线工作的方式。NULL
bounds
overview_polyline
那么这里有什么问题呢?NULL
为什么 Google Directions API在我需要时会提供这么多对象?
谢谢!