如何将MKCircleView在一个位置移动到MKMapView中的另一个位置?

时间:2013-08-23 13:55:54

标签: ios objective-c touch mkmapview uitapgesturerecognizer

我使用MkCircle声明位置现在我必须在MKMapView(Drag& Drop)中将Circle位置改变一个位置到另一个位置。我怎样才能做到这一点。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

首先,我建议你有一些类属性来跟踪叠加层:

@property (nonatomic, weak) MKCircle *overlay;

然后,定义UIPanGestureRecognizer以执行拖放操作:

UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[self.mapView addGestureRecognizer:pan];

要使手势取消,您应该导入以下标题:

#import <UIKit/UIGestureRecognizerSubclass.h>

你需要为这个手势识别器编写一个处理程序,为你拖动的位置添加一个叠加并删除旧的(但如果它没有从叠加层开始,则取消手势):

- (void)handlePan:(UIPanGestureRecognizer *)gesture
{
    static CGPoint originalPoint;

    if (gesture.state == UIGestureRecognizerStateBegan) {
        CGPoint point = [gesture locationInView:gesture.view];
        CLLocationCoordinate2D tapCoordinate = [self.mapView convertPoint:point toCoordinateFromView:gesture.view];
        CLLocation *tapLocation = [[CLLocation alloc] initWithLatitude:tapCoordinate.latitude longitude:tapCoordinate.longitude];

        CLLocationCoordinate2D originalCoordinate = [self.overlay coordinate];
        CLLocation *originalLocation = [[CLLocation alloc] initWithLatitude:originalCoordinate.latitude longitude:originalCoordinate.longitude];

        if ([tapLocation distanceFromLocation:originalLocation] > [self.overlay radius]) {
            gesture.state = UIGestureRecognizerStateCancelled;
            return;
        }
        else
            originalPoint = [self.mapView convertCoordinate:originalCoordinate toPointToView:gesture.view];
    }

    if (gesture.state == UIGestureRecognizerStateChanged) {
        CGPoint translation = [gesture translationInView:gesture.view];
        CGPoint newPoint    = CGPointMake(originalPoint.x + translation.x, originalPoint.y + translation.y);

        CLLocationCoordinate2D newCoordinate = [self.mapView convertPoint:newPoint toCoordinateFromView:gesture.view];

        MKCircle *circle = [MKCircle circleWithCenterCoordinate:newCoordinate radius:[self.overlay radius]];
        [self.mapView addOverlay:circle];
        [self.mapView removeOverlay:self.overlay];
        self.overlay = circle;
    }
}

注意,必须关闭地图的scrollEnabled才能识别此手势。