MKMapView zooms itself out

1.4k views Asked by At

This is a small method of mine which takes the location manager's current location and focuses the map just a little bit above it to make room for some other subviews that I've added to the top of the map. If the span's lat/long deltas get too big (more than 1.0), every time the region is set, the span gets bigger and bigger until the map is zoomed out all the way, even without actually touching the map. I think it has something to do with reusing the map view's span, but I don't know exactly what's going on.

- (void)setRegion {
    CLLocationCoordinate2D coord = locationManager.location.coordinate;

    MKCoordinateSpan span = mapView.region.span;

    coord.latitude += 0.002 * (span.latitudeDelta / 0.012523);

    MKCoordinateRegion region = MKCoordinateRegionMake(coord, span);
    [mapViewGlobal setRegion:region animated:animated];
}
1

There are 1 answers

2
Craig On BEST ANSWER

From Apple's docs "If you want to change the center coordinate without changing the zoom level, use the setCenterCoordinate:animated: instead." MKMapView

- (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)animated

MKMapView will pick a new region that nicely fits the to a redefined zoom level while still displaying your entire target region and each time yo move north the span changes and things spiral out of control.

Also, your way of working out how much to change the latitude by is a bit odd. Aside from doing a multiple and divide when one would do the trick, it'll only work at a certain latitude (they get stretched away from the equator) and a certain zoom level. You'd be better off working out how many pixels you need the map scrolled by (presumably half the height of your subviews) and then using this function to work out where you need to center the map.

- (CLLocationCoordinate2D)convertPoint:(CGPoint)point toCoordinateFromView:(UIView *)view

Another way would be to put the subviews outside of the MKMapView, but that'll affect your aesthetics.