18

我想在我的 mapView 中显示一个点对点的路线,我使用这个代码来创建路线:

- (IBAction)backToYourCar {
    MKPlacemark *sourcePlacemark = [[MKPlacemark alloc] initWithCoordinate:self.annotationForCar.coordinate addressDictionary:nil];
    NSLog(@"coordiante : locationIniziale %f", sourcePlacemark.coordinate.latitude);
    MKMapItem *carPosition = [[MKMapItem alloc] initWithPlacemark:sourcePlacemark];
    MKMapItem *actualPosition = [MKMapItem mapItemForCurrentLocation];
    NSLog(@"coordiante : source %f, ActualPosition %f", carPosition.placemark.coordinate.latitude ,actualPosition.placemark.coordinate.latitude);
    MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
    request.source = actualPosition;
    request.destination = carPosition;
    request.requestsAlternateRoutes = YES;

    MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
    [directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
        if (error) {
            NSLog(@"Error : %@", error);
        }
        else {
            [self showDirections:response]; //response is provided by the CompletionHandler
        }
    }];
}

这用于在地图上显示路线:

- (void)showDirections:(MKDirectionsResponse *)response
{
    for (MKRoute *route in response.routes) {
        [self.mapView addOverlay:route.polyline level:MKOverlayLevelAboveRoads];
    }
}

实际上这段代码什么都不做。

如果我尝试打印路线的距离,我会得到正确的值:

route distance: 1910.000000

那么路线是对的,但我不明白为什么它没有出现在地图上!

有什么建议么?

4

1 回答 1

50

经过一天的研究,我已经解决了这三个步骤:

  1. 设置委托 ( self.mapView.delegate = self)。
  2. 导入MKMapViewDelegate
  3. 实现新的 iOS7 MapView 委托方法 - (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay(id<MKOverlay>)overlay

这是我的实现:

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
    if ([overlay isKindOfClass:[MKPolyline class]]) {
        MKPolyline *route = overlay;
        MKPolylineRenderer *routeRenderer = [[MKPolylineRenderer alloc] initWithPolyline:route];
        routeRenderer.strokeColor = [UIColor blueColor];
        return routeRenderer;
    }
    else return nil;
}

当您在地图上添加折线时,委托会自动调用此方法。

于 2013-09-15T22:00:59.677 回答