在iOS地圖上繪制兩點間路線

jopen 12年前發布 | 38K 次閱讀 IOS 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)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地圖上繪制兩點間路線

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

Jason Lee @ Hangzhou

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!