Search code examples
iphonemkmapviewzoomingregion

How can I set MKMapView's region span dynamically so that it doesn't "snap" back to the initial Region upon redrawing the map?


I am working with a MKMapview and I am having a problem with the zoom level and the region span.

It would seem when the MKMapView is refreshed it resets the region to the values that have been hardcoded when I initially installed them. I am keeping track of the user's location and with any changes in the location of the phone the map should update via the CLLocationManagerDelegate and the delegate method listed below.

Currently I have this in the locationManager:didUpdateToLocation:fromLocation:

    MKCoordinateSpan span;
    span.latitudeDelta =  0.8;  
    span.longitudeDelta = 0.8;     
    MKCoordinateRegion region;
    region.center = newLocation.coordinate;
    region.span = span;
    [self.MyMapView setRegion:region animated:NO];

I have also tried putting similar code in the viewDidLoad: to no avail. My thinking is that I could somehow set the region dynamically in the

-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated

delegate method I could sidestep this issue entirely but I am not exactly sure how I should do that.

Ultimately I'd just like to have the map stop "snapping" back to the above span. Thanks in advance.


Solution

  • If you're trying to keep the map centered on the user's current location, first decide whether you want to use:

    • the map view's userLocation property and the map view's delegate method mapView:didUpdateUserLocation:, or
    • the CLLocationManager and its delegate method locationManager:didUpdateToLocation:fromLocation:

    With either one, in viewDidLoad, you should just set the map view's initial region including center (using some default coordinate) and span. The user's location will be unlikely to be available immediately in viewDidLoad as it can take a few seconds to acquire.

    Trying to use userLocation before its set may cause an exception when setting the region with that value.

    If using the map view's userLocation, then:

    • in viewDidLoad or IB, set mapView.showsUserLocation to YES
    • in the mapView:didUpdateUserLocation: method, do mapView.centerCoordinate = userLocation.location.coordinate; (or use setCenterCoordinate:animated:)
    • recommend also implementing mapView:didFailToLocateUserWithError: to handle or at least become aware of failures

    If using the CLLocationManager, then:

    • in viewDidLoad, do [locationManager startUpdatingLocation];
    • in the locationManager:didUpdateToLocation:fromLocation: method, do mapView.centerCoordinate = newLocation.coordinate; (or use the animated method)
    • recommend also implementing locationManager:didFailWithError: to handle or at least become aware of failures