Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MKMapView setRegion: crashes at edge of world

I am using this code to set the region of an MKMapView such that it is centred around pin and zoomed to show an approximate 10km area.

CLLocationAccuracy accuracy = kCLLocationAccuracyKilometer;
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(pin.coordinate, accuracy * 10.0f, accuracy * 10.0f);
[self.mapSubView setRegion:region animated:NO];

When running the code with a pin coordinate of latitude -90, longitude -58.359001159667969 the region is generated as shown:

A crash occurs when the mapSubView is drawn:-

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid Region <center:-90.00000000, -58.35900116 span:+0.08953039, +1462142065660629.00000000>'

My first attempt at fixing this was to check for "edge" lat/long (-90, +90, -180, +180), which solved the issue. However if the latitude changes to -89.99999 the problem returns.

I'm guessing this is due to a combination of the latitude being -90 and/or the region span's longitude delta being so large resulting in a region that is effectively "out of this world" :p

Any advice as to how to centre the map around a pin at any coordinate, showing a ~10km area, without this crash would be greatly appreciated.

like image 665
Steve Wilford Avatar asked Apr 16 '14 14:04

Steve Wilford


1 Answers

@supp-f answer is right

Swift 3 solution:

func safeSetRegion(_ region: MKCoordinateRegion) {
    let myRegion = self.mapView.regionThatFits(region)
    if !(myRegion.span.latitudeDelta.isNaN || myRegion.span.longitudeDelta.isNaN) {
        self.mapView.setRegion(myRegion, animated: true)
    }
}
like image 67
Sergey Teryokhin Avatar answered Oct 12 '22 07:10

Sergey Teryokhin