您的位置:首页 > 移动开发 > IOS开发

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

2016-01-08 17:51 671 查看
http://blog.csdn.net/jasonblog/article/details/7785352

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

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

[cpp] view
plaincopy

#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协议,但并不能作为遮罩。我们需要实现相应的遮罩代理方法:

[cpp] view
plaincopy

#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;  

}  

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

[cpp] view
plaincopy

- (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];  

}  

绘制结果如下:



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

Jason Lee @ Hangzhou
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: