Search code examples
iosdrag-and-dropmkmapviewmkannotationview

MKMapView pin drag from another view


I'm thinking about a Google Map street view pin drag and drop system on iOS. The user selects a pin from another view (let's say UINavigationBar) and drag it to a position on map and then drop it.

I'm a bit lost with it. Do you have a workflow for this type of interaction ?


Solution

  • It is quite a complex task but it can be divided into a couple of simple steps.

    1. Make a custom UIView, which after touching will follow the touch movement.

    Example

    -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        _originalPosition = self.view.center;
        _touchOffset = CGPointMake(self.view.center.x-position.x,self.view.center.y-position.y);
    }
    
    -(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
    {        
        UITouch *touch = [touches anyObject];
        CGPoint position = [touch locationInView: self.view.superview];
    
        [UIView animateWithDuration:.001
                              delay:0.0
                            options:UIViewAnimationOptionCurveEaseInOut
                         animations:^ {
    
                             self.view.center = CGPointMake(position.x+_touchOffset.x, position.y+_touchOffset.y);
                         }
                         completion:^(BOOL finished) {}];
    }
    
    -(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    {
        CGPoint positionInView = [touch locationInView:self.view];
        CGPoint newPosition;
        if (CGRectContainsPoint(_desiredView.frame, positionInView)) {
            newPosition = positionInView;
            // _desiredView is view where the user can drag the view
        } else {
            newPosition = _originalPosition;
            // its outside the desired view so lets move the view back to start position
        }
    
        [UIView animateWithDuration:0.4
                              delay:0.0
                            options:UIViewAnimationOptionCurveEaseInOut
                         animations:^ {
                             self.view.center = newPosition
                             // to 
                         }
                         completion:^(BOOL finished) {}];
    
    }
    
    1. When user releases the finger, you will have to get the location of the touch.
    2. Calculate the touch location in map view coordinates and place the pin.

    Hope it points you to the right direction.