azamsharp
azamsharp

Reputation: 20068

Convert MKAnnotation Coordinates to View Coordinates

I am displaying a custom UIView when the user clicks on the pin (Like the Zillow app). Now the problem is that I need to place the view right above the actual pin. The MKAnnotationView coordinates system is related to the map. How can I get the coordinates with respect to the iPhone screen and then place my view on that coordinate.

- (void)mapView:(MKMapView *)mv didSelectAnnotationView:(MKAnnotationView *)view
{  
    // get view from storyboard 
    ZillowSearchResultAnnotation *annotation = (ZillowSearchResultAnnotation *) view.annotation;

    PropertyAbstractViewController *propertyAbstractViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PropertyAbstractIdentifier"];
    propertyAbstractViewController.view.frame = CGRectMake(0, 0, 100, 100);

    [propertyAbstractViewController bind:annotation.data];

    [mv addSubview:propertyAbstractViewController.view];

}

Upvotes: 3

Views: 3190

Answers (2)

Siddhartha Moraes
Siddhartha Moraes

Reputation: 184

This is perfect, but there is one little problem. If you use a different image to your Pin, than you will need make a correction to Your view Appoint to center of your pin. Like this

UIView *view = ...
CGPoint p = [mv convertCoordinate:annotation.coordinate toPointToView:mv];
CGRect frame = CGRectMake(p.x - (view.frame.size.width/2), 
                          p.y- (view.frame.size.height / 2),
                          view.frame.size.width,
                          view.frame.size.height);
view.frame = frame;
[self.view addSubView:view];

Upvotes: 1

Jano
Jano

Reputation: 63667

Use convertCoordinate:toPointToView:. Something like:

UIView *view = ...
CGPoint p = [mv convertCoordinate:annotation.coordinate toPointToView:mv];
CGRect frame = CGRectMake(p.x,p.y,view.frame.size.width,view.frame.size.height);
view.frame = frame;
[self.view addSubView:view];

Upvotes: 12

Related Questions