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

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

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

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

MKPolyLine爲我們提供了方便繪製多條線段的功能,它實現了MKOverlay協議,但並不能作爲遮罩。我們需要實現相應的遮罩代理方法:

  1. #pragma mark - MKMapViewDelegate  
  2.   
  3. - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay  
  4. {  
  5.     if(overlay == self.routeLine) {  
  6.         if(nil == self.routeLineView) {  
  7.             self.routeLineView = [[[MKPolylineView alloc] initWithPolyline:self.routeLine] autorelease];  
  8.             self.routeLineView.fillColor = [UIColor redColor];  
  9.             self.routeLineView.strokeColor = [UIColor redColor];  
  10.             self.routeLineView.lineWidth = 5;  
  11.         }  
  12.         return self.routeLineView;  
  13.     }  
  14.     return nil;  
  15. }  

下面是我的測試代碼,用北京的經緯度和杭州的經緯度畫線:

  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. }  

繪製結果如下:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章