Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move MKMapView based on selected annotation

I have an MKMapView which populates the entirety of my view, but when a pin is selected, I am sliding up another view on top of the map. I want to move the map so the pin will appear in the centre of the visible area of the map.

Difficult to explain but hopefully it makes sense! Thanks in advance.

like image 374
Ricky Avatar asked Mar 15 '11 00:03

Ricky


1 Answers

You could try getting the MKMapRect from visibleMapRect for the map view, converting the annotation's coordinate to an MKMapPoint, resetting the MKMapRect's origin so the MKMapPoint is in the appropriate position, and then using setVisibleMapRect:animated: to set the visible region to the new MKMapRect.

For example, if you wanted to move the map so the annotation is centered horizontally and 25% of the way down vertically, you could do something like this:

MKMapRect r = [mapView visibleMapRect];
MKMapPoint pt = MKMapPointForCoordinate([annotation coordinate]);
r.origin.x = pt.x - r.size.width * 0.5;
r.origin.y = pt.y - r.size.height * 0.25;
[mapView setVisibleMapRect:r animated:YES]; 
like image 125
Anomie Avatar answered Oct 14 '22 23:10

Anomie