在iOS 7中使用谷歌地图绘制折线?

时间:2013-12-11 07:00:08

标签: iphone objective-c google-maps ios7

使用此link

我试图从一个坐标到另一个坐标获得路线方向,但没有得到路线。下面提到使用编码......

        NSArray *routesArray = [res objectForKey:@"routes"]; 
        NSDictionary *routeDict = [routesArray objectAtIndex:0];
        NSDictionary *routeOverviewPolyline = [routeDict objectForKey:@"overview_polyline"];
        NSString *points = [routeOverviewPolyline objectForKey:@"points"];
        GMSPath *path = [GMSPath pathFromEncodedPath:points];

        polyline = [GMSPolyline polylineWithPath:path];
        polyline.strokeColor = [UIColor greenColor];
        polyline.strokeWidth = 10.f;

        polyline.map = mapView_;

有谁知道。帮我解决这个问题..

1 个答案:

答案 0 :(得分:10)

您可以使用GoogleMapsDirectionGoogle 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非常有用。