eric eric - 1 year ago 127
iOS Question

Centering MKMapView on spot N-pixels below pin

Want to center MKMapView on a point N-pixels below a given pin (which may or may not be visible in the current MapRect).

I've been trying to solve this using various plays with

-(CLLocationCoordinate2D)convertPoint:(CGPoint)point toCoordinateFromView:(UIView *)view
to no success.

Anyone been down this road (no pun intended)?

enter image description here

Rob Rob
Answer Source

The easiest technique that I can think of would be to just shift the map down, say 40% from where the coordinate would be, taking advantage of the span of the region of the MKMapView. If you don't need actual pixels, but just need it to move down so that the CLLocationCoordinate2D in question is near the top of the map (say 10% away from the top):

CLLocationCoordinate2D center = coordinate;
center.latitude -= self.mapView.region.span.latitudeDelta * 0.40;
[self.mapView setCenterCoordinate:center animated:YES];

Original answer: for moving the annotation n pixels

If you have a CLLocationCoordinate2D, you can convert it to a CGPoint, move it x pixels, and then convert it back to a CLLocationCoordinate2D:

- (void)moveCenterByOffset:(CGPoint)offset from:(CLLocationCoordinate2D)coordinate
    CGPoint point = [self.mapView convertCoordinate:coordinate toPointToView:self.mapView];
    point.x += offset.x;
    point.y += offset.y;
    CLLocationCoordinate2D center = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
    [self.mapView setCenterCoordinate:center animated:YES];

You can call this by:

[self moveCenterByOffset:CGPointMake(0, 100) from:coordinate];

Unfortunately, this only works if the coordinate is visible before you start, so you might have to go to the original coordinate first, and then adjust the center.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download