您可以使用GoogleMapsDirection 从Google Directions API 获取路径或DirectionResponse。 NSLogs 对于查看您正在处理的内容很有用。
[[GMDirectionService sharedInstance] getDirectionsFrom:origin to:destination succeeded:^(GMDirection *directionResponse) {
if ([directionResponse statusOK]){
NSLog(@"Duration : %@", [directionResponse durationHumanized]);
NSLog(@"Distance : %@", [directionResponse distanceHumanized]);
NSArray *routes = [[directionResponse directionResponse] objectForKey:@"routes"];
// NSLog(@"Route : %@", [[directionResponse directionResponse] objectForKey:@"routes"]);
}
} failed:^(NSError *error) {
NSLog(@"Can't reach the server")
}];
一旦你有了 json,你就可以得到路径点(这显示了索引 0 处的第一条路线)。
GMSPath *path = [GMSPath pathFromEncodedPath:routes[0][@"overview_polyline"][@"points"]];
然后您可以将路径转换为折线并将其绘制在您的 mapView 上,并根据需要设置 strokeColor 和 strokeWidth。
GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
polyline.strokeColor = [UIColor redColor];
polyline.strokeWidth = 5.f;
然后将 polyline.map 属性设置为您的 mapView。
polyline.map = mapView;
终于把所有东西放在一起
[[GMDirectionService sharedInstance] getDirectionsFrom:origin to:destination succeeded:^(GMDirection *directionResponse) {
if ([directionResponse statusOK]){
NSLog(@"Duration : %@", [directionResponse durationHumanized]);
NSLog(@"Distance : %@", [directionResponse distanceHumanized]);
NSArray *routes = [[directionResponse directionResponse] objectForKey:@"routes"];
// NSLog(@"Route : %@", [[directionResponse directionResponse] objectForKey:@"routes"]);
GMSPath *path = [GMSPath pathFromEncodedPath:routes[0][@"overview_polyline"] [@"points"]];
GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
polyline.strokeColor = [UIColor redColor];
polyline.strokeWidth = 5.f;
polyline.map = mapView;
}
} failed:^(NSError *error) {
NSLog(@"Can't reach the server")
}];
我发现CocoaPods 对于安装 Google Maps SDK 和 GoogleMapsDirection 很有用。