如何从Google Directions API迭代路径?

时间:2017-04-26 09:45:40

标签: ios google-maps google-polyline

我正在尝试沿着两个选定的标记移动标记,并设置坐标。

我从这段代码中获取路径:

GMSPath *path1 =[GMSPath pathFromEncodedPath:self.dataReceive[@"routes"][0][@"overview_polyline"][@"points"]];

当我使用for循环将第一个标记移动到第二个标记的位置时。它采用直线路径,但应沿着从Google方向API获取的路径坐标移动。

    for (int i = 0; i< path1.count; i++) {

        CLLocationCoordinate2D position = [path1 coordinateAtIndex:i];
        [CATransaction begin];
        [CATransaction setAnimationDuration:50];
        self.marker.position = position;
        self.marker.map = self.mapView;
        [CATransaction commit];
    }

感谢。

1 个答案:

答案 0 :(得分:0)

  

尝试此代码目标C。

 - (void)showPathFromCurrentLocationForCoordinate:(CLLocationCoordinate2D)coord{
CLLocationCoordinate2D destination = coord;
NSMutableString *urlString = [[NSMutableString alloc] initWithString:@"https://maps.googleapis.com/maps/api/directions/json?"];
[urlString appendString:[NSString stringWithFormat:@"origin=%f,%f&destination=%f,%f&sensor=true",self.deviceLocation.latitude,self.deviceLocation.longitude,destination.latitude,destination.longitude]];

[RestApi getPath:urlString withParameter:nil withHandler:^(id responseObject, NSError *error, NSURLResponse *response) {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (error == nil) {
            NSDictionary *json = responseObject;
            NSArray *routes = [json objectForKey:@"routes"];
            if (routes != nil && routes.count > 0) {
                NSDictionary *route = [routes objectAtIndex:0];
                long distance = 0;
                NSArray *legs = [route objectForKey:@"legs"];
                for (NSDictionary *leg in legs) {
                    long dist = [leg[@"distance"][@"value"] longValue];
                    distance = distance + dist;
                }
                GMSPath *path =[GMSPath pathFromEncodedPath:route[@"overview_polyline"][@"points"]];
                GMSPolyline *line = [GMSPolyline polylineWithPath:path];
                line.strokeColor = PATH_STROKE_COLOR;
                line.strokeWidth = PATH_STROKE_WIDTH;
                line.map = mapView;
                GMSMutablePath *markerpath = [GMSMutablePath path];
                [markerpath addCoordinate: self.deviceLocation];
                [markerpath addCoordinate: marker.position];

                GMSCoordinateBounds *bonds = [[GMSCoordinateBounds alloc] initWithPath:markerpath];
                [CATransaction begin];
                [CATransaction setValue:[NSNumber numberWithFloat: 1.0] forKey:kCATransactionAnimationDuration];
                [mapView animateWithCameraUpdate:[GMSCameraUpdate fitBounds:bonds withPadding:MAP_BOUNDS_OFFSET_PADDING]];
                [CATransaction commit];
            }
            else{
                NSLog(@"Google direction API failed.");
            }
        }
        else if (error != nil){
            NSLog(@"%@",error.localizedDescription);
        }
    });
}];

}

相关问题