Exception : 'Invalid Region <center:+inf, +0.00000000 span:+1.00000000, +0.50000000>' when trying to display the map

In some situations (when the app becomes active from background) didUpdateUserLocation method is fired, but without updated location. In these cases there is no valid region, and setRegion: method can throw an exception. Stupid, a simple solution can be checking if its region is valid before you set it:

 if(region.center.longitude == -180.00000000){
    NSLog(@"Invalid region!");
}else{
    [aMapView setRegion:region animated:YES];
}

"Invalid Region" exception is through because the region you set to mapView is invalid. As I know now, there are 2 reasons can cause this exception: region's center point is invalid, or region's span is invalid.

To avoid this exception:
1) Check the center point value: latitude is in range [-90;90], longitude is in range [-180;180]
2) Use [mapView regionThatFits:region] to get a region with valid span then set to mapview:
[mapView setRegion:[mapView regionThatFits:region]]


After calling startUpdatingLocation, it may take a few seconds for the location to be updated so you can't try to retrieve it immediately afterwards. Until it is updated, location contains invalid values which is what the error tells you.

Instead, implement the locationManager:didUpdateToLocation:fromLocation: delegate method and read the location in there.

Move all the code after startUpdatingLocation to that method:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    CLLocation *location = [locationManager location];
    //etc...
}

Note: above method is depriciated: Apple Doc

Tags:

Ios

Mapkit