在iOS地图上绘制两点间路线

当我们获取了一组地理位置后,可能会想要在地图上绘制这组地理位置信息所包含的路线。

MKMapView提供了addOverlay功能(以及addAnnotation),让我们可以在地图上放一层遮罩。如果要放一组遮罩,可以用addOverlays。

#pragma mark - 

- (void)drawLineWithLocationArray:(NSArray *)locationArray
{
    int pointCount = [locationArray count];
    CLLocationCoordinate2D *coordinateArray = (CLLocationCoordinate2D *)malloc(pointCount * sizeof(CLLocationCoordinate2D));
    
    for (int i = 0; i < pointCount; ++i) {
        CLLocation *location = [locationArray objectAtIndex:i];
        coordinateArray[i] = [location coordinate];
    }
    
    self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:pointCount];
    [self.mapView setVisibleMapRect:[self.routeLine boundingMapRect]];
    [self.mapView addOverlay:self.routeLine];
    
    free(coordinateArray);
    coordinateArray = NULL;
}

MKPolyLine为我们提供了方便绘制多条线段的功能,它实现了MKOverlay协议,但并不能作为遮罩。我们需要实现相应的遮罩代理方法:

#pragma mark - MKMapViewDelegate

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
{
    if(overlay == self.routeLine) {
        if(nil == self.routeLineView) {
            self.routeLineView = [[[MKPolylineView alloc] initWithPolyline:self.routeLine] autorelease];
            self.routeLineView.fillColor = [UIColor redColor];
            self.routeLineView.strokeColor = [UIColor redColor];
            self.routeLineView.lineWidth = 5;
        }
        return self.routeLineView;
    }
    return nil;
}

下面是我的测试代码,用北京的经纬度和杭州的经纬度画线:

- (void)drawTestLine
{
    CLLocation *location0 = [[CLLocation alloc] initWithLatitude:39.954245 longitude:116.312455];
    CLLocation *location1 = [[CLLocation alloc] initWithLatitude:30.247871 longitude:120.127683];
    NSArray *array = [NSArray arrayWithObjects:location0, location1, nil];
    [self drawLineWithLocationArray:array];
}

绘制结果如下:

在iOS地图上绘制两点间路线_第1张图片

原文地址:http://blog.csdn.net/jasonblog/article/details/7785352

Jason Lee @ Hangzhou

你可能感兴趣的:(ios,测试,null,CLLocation)