2

I am Declare locations by using MkCircle Now I have to change Circle position one place to another place in MKMapView(Drag & Drop). how can i achieve this. Any help will be appreciated.

Marco
  • 6,692
  • 2
  • 27
  • 38
Chithri Ajay
  • 907
  • 3
  • 16
  • 37

1 Answers1

3

First, I'd suggest you have some class property to keep track of the overlay:

@property (nonatomic, weak) MKCircle *overlay;

Then, define a UIPanGestureRecognizer to perform the drag and drop:

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

To make the gesture cancelable, you should import the following header:

#import <UIKit/UIGestureRecognizerSubclass.h>

And you need to write a handler for this gesture recognizer that adds an overlay for where you dragged and removes the old one (but cancels the gesture if it didn't start over the overlay):

- (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;
    }
}

Note, the map's scrollEnabled has to be turned off for this gesture to be recognized.

Rob
  • 415,655
  • 72
  • 787
  • 1,044