如何正确地实现地图标注动画移动?

3
我正在 MKMapView 上显示城市公交车的实时位置。我的应用程序以一定的间隔轮询位置,并在地图上更新它们。我尝试使用以下代码动画移动地图标注:
我成功地使用下面这段代码实现了动画移动,这段代码来自于这个stackoverflow答案:
- (void)moveBusAnnotation:(TKLBus*)bus coordinate:(CLLocationCoordinate2D)coordinate {
    [UIView animateWithDuration:0.5f
    animations:^(void){
        bus.annotation.coordinate = coordinate;
    }];
}

问题是当用户在动画播放时平移或缩放地图时,注释的运动路径会看起来很奇怪和错误。以下是演示:
请注意,地图注释遵循了一个奇怪的曲线而不是直线。公交车运动是模拟的,所以忽略它在地图上的奇怪位置。 如何使动画看起来更自然或停止动画,同时地图被平移/缩放?
编辑:动画似乎做得没错。它看起来奇怪只是因为地图注释的下一个坐标在动画播放时移动了。我认为解决方案是在用户触摸屏幕时阻止动画。
1个回答

1

请尝试以下操作:

设置一个布尔变量,用于指示用户是否正在使用地图:

@property (nonatomic, assign) BOOL userIsInteracting;

然后检查地图上的用户触摸:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];

    for (UITouch * touch in touches) 
    {
        CGPoint loc = [touch locationInView:_mapView];
        if ([_mapView pointInside:loc withEvent:event]) 
        {
            _userIsInteracting = YES;
            break;
        }
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];

    for (UITouch * touch in touches) 
    {
        CGPoint loc = [touch locationInView:_mapView];
        if ([_mapView pointInside:loc withEvent:event]) 
        {
            _userIsInteracting = NO;
            break;
        }
    }
}

现在你知道何时在地图上动画显示位置了:
- (void)moveBusAnnotation:(TKLBus*)bus coordinate:(CLLocationCoordinate2D)coordinate 
{
    if (_userIsInteracting) return;

    [UIView animateWithDuration:0.5f
                     animations:^(void){
                     bus.annotation.coordinate = coordinate;
                     }];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接