你可以做的是在你的视图控制器中,实现MKMapViewDelegate
协议,当你的叠加层被添加时,它会给你回调。您可以实现一种仅绘制一条线段(两个点)的方法,并在每次收到添加了另一条线叠加的通知时触发该方法。
在视图控制器中声明一些实例变量:
@interface ViewController : UIViewController<MKMapViewDelegate> {
@private
MKMapView* mapView;
CLLocationCoordinate2D coordinates[4];
int lineNumber;
BOOL isPaused;
}
@property (strong, nonatomic) IBOutlet MKMapView *mapView;
然后在您的视图控制器 .m 文件中:
- (void)addNextLine {
if (!isPaused) {
// move to the next line
lineNumber++;
MKPolyline* line = [MKPolyline polylineWithCoordinates: &coordinates[lineNumber - 1]
count: 2];
[self.mapView addOverlay: line];
}
}
- (void)drawPolylines {
isPaused = NO;
// initialize the list of coordinates for the line segments
coordinates[0] = CLLocationCoordinate2DMake(47.8, -122.0);
coordinates[1] = CLLocationCoordinate2DMake(47.9, -122.0);
coordinates[2] = CLLocationCoordinate2DMake(47.9, -122.1);
coordinates[3] = CLLocationCoordinate2DMake(48.0, -122.1);
lineNumber = 0;
self.mapView.region = MKCoordinateRegionMake(coordinates[0], MKCoordinateSpanMake(0.2, 0.2));
// start adding lines one at a time
[self addNextLine];
}
// MKMapViewDelegate callback when an overlay has been added
- (void)mapView:(MKMapView *)theMap didAddOverlayViews:(NSArray *)overlayViews {
if (lineNumber < 3) {
// schedule the next line segment to be drawn after a 2 second delay:
[self performSelector: @selector(addNextLine) withObject:nil afterDelay: 2.0f];
}
}
// MKMapViewDelegate callback when an overlay's view needs to be generated
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id < MKOverlay >)overlay {
if ([[overlay class] isSubclassOfClass: [MKPolyline class]]) {
MKPolylineView* view = [[MKPolylineView alloc] initWithPolyline: overlay];
view.strokeColor = [UIColor redColor];
view.lineWidth = 2;
view.fillColor = [UIColor redColor];
return view;
}
return nil;
}
您可以通过调用来触发整个过程:
[self drawPolylines];
在我的代码中,添加的每一行之间有 2 秒的延迟。如果您愿意,可以删除/更改它。
编辑:为了使用按钮开始和暂停该过程,请将您UIButton
的 s 连接到这些操作:
-(IBAction)onStart: (id)sender {
if (isPaused) {
isPaused = NO;
[self addNextLine];
} else {
[self drawPolylines];
}
}
-(IBAction)onPause: (id)sender {
isPaused = YES;
}