IOS 在iOS地圖上繪製兩點間路線
阿新 • • 發佈:2019-01-27
當我們獲取了一組地理位置後,可能會想要在地圖上繪製這組地理位置資訊所包含的路線。
MKMapView提供了addOverlay功能(以及addAnnotation),讓我們可以在地圖上放一層遮罩。如果要放一組遮罩,可以用addOverlays。
- #pragma mark -
- - (void)drawLineWithLocationArray:(NSArray *)locationArray
- {
- int pointCount = [locationArray count];
-
CLLocationCoordinate2D *coordinateArray = (CLLocationCoordinate2D *)malloc(pointCount * sizeof
- 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];
- }
繪製結果如下: