1. 程式人生 > >IOS 在iOS地圖上繪製兩點間路線

IOS 在iOS地圖上繪製兩點間路線

當我們獲取了一組地理位置後,可能會想要在地圖上繪製這組地理位置資訊所包含的路線。

MKMapView提供了addOverlay功能(以及addAnnotation),讓我們可以在地圖上放一層遮罩。如果要放一組遮罩,可以用addOverlays。

  1. #pragma mark - 
  2. - (void)drawLineWithLocationArray:(NSArray *)locationArray  
  3. {  
  4.     int pointCount = [locationArray count];  
  5.     CLLocationCoordinate2D *coordinateArray = (CLLocationCoordinate2D *)malloc(pointCount * sizeof
    (CLLocationCoordinate2D));  
  6.     for (int i = 0; i < pointCount; ++i) {  
  7.         CLLocation *location = [locationArray objectAtIndex:i];  
  8.         coordinateArray[i] = [location coordinate];  
  9.     }  
  10.     self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:pointCount];  
  11.     [self.mapView setVisibleMapRect:[self.routeLine boundingMapRect]];  
  12.     [self.mapView addOverlay:self.routeLine];  
  13.     free(coordinateArray);  
  14.     coordinateArray = NULL;  
  15. }  

MKPolyLine為我們提供了方便繪製多條線段的功能,它實現了MKOverlay協議,但並不能作為遮罩。我們需要實現相應的遮罩代理方法:
  1. #pragma mark - MKMapViewDelegate
  2. - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay  
  3. {  
  4.     if(overlay == self.routeLine) {  
  5.         if(nil == self.routeLineView) {  
  6.             self.routeLineView = [[[MKPolylineView alloc] initWithPolyline:self.routeLine] autorelease];  
  7.             self.routeLineView.fillColor = [UIColor redColor];  
  8.             self.routeLineView.strokeColor = [UIColor redColor];  
  9.             self.routeLineView.lineWidth = 5;  
  10.         }  
  11.         return self.routeLineView;  
  12.     }  
  13.     return nil;  
  14. }  

下面是我的測試程式碼,用北京的經緯度和杭州的經緯度畫線:
  1. - (void)drawTestLine  
  2. {  
  3.     CLLocation *location0 = [[CLLocation alloc] initWithLatitude:39.954245 longitude:116.312455];  
  4.     CLLocation *location1 = [[CLLocation alloc] initWithLatitude:30.247871 longitude:120.127683];  
  5.     NSArray *array = [NSArray arrayWithObjects:location0, location1, nil];  
  6.     [self drawLineWithLocationArray:array];  
  7. }  

繪製結果如下: