MapView setRigion崩溃问题

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid Region '
*** First throw call stack:
(0x186626fe0 0x185088538 0x186626ca8 0x192cff0cc 0x1000aa850 0x18c751b04 0x18c769590 0x18c8ede18 0x18c8087bc 0x18c808424 0x18c808388 0x18c74ecc0 0x18993f274 0x189933de8 0x189933ca8 0x1898af34c 0x1898d63ac 0x1898d6e78 0x1865d49a8 0x1865d2630 0x1865d2a7c 0x186502da4 0x187f6d074 0x18c7b6c9c 0x1002dfc38 0x18551159c)
libc++abi.dylib: terminating with uncaught exception of type NSException

看到这个报错信息,大概能知道是Region的参数不合法,造成在setRegion:时抛出异常,程序崩溃

打印theRegion

Printing description of theRegion:
(MKCoordinateRegion) theRegion = {
  center = (latitude = 141, longitude = 23)
  span = (latitudeDelta = 0.050000000000000003, longitudeDelta = 0.050000000000000003)
}

这时我们看到经纬度是一个整数,很明显这不是一个合格的经纬度。

这是一个正常的theRegion

Printing description of theRegion:
(MKCoordinateRegion) theRegion = {
  center = (latitude = 40.0166015625, longitude = 116.50270080566406)
  span = (latitudeDelta = 0.050000000000000003, longitudeDelta = 0.050000000000000003)
}

可能是有时候经纬度数据不是通过正确手段录入的,可能有的是错误数据,但并不是每一个数字都可以是一个合格的经纬度。因此我们需要判断一下这个经纬度是不是合法的。

通过这个方法判断

theRegion = [_mapView regionThatFits:theRegion];

此时经过转换后的theRegion

Printing description of theRegion:
(MKCoordinateRegion) theRegion = {
  center = (latitude = -180, longitude = -180)
  span = (latitudeDelta = NaN, longitudeDelta = NaN)
}

我们可以看到span = (latitudeDelta ,longitudeDelta)的值便不是你开始设的值,而会变为NaN(nan)

因此我们通过上述方法转换后再判断span = (latitudeDelta ,longitudeDelta)的值之后再决定是否setRegion:

具体代码如下:

MKCoordinateSpan theSpan;
    
    //地图的范围 越小越精确
    theSpan.latitudeDelta = 0.05;
    theSpan.longitudeDelta = 0.05;
    MKCoordinateRegion theRegion;
    NSString *latt = [NSString stringWithFormat:@"%.6f", self.coordinate.latitude];
    double latti = [latt doubleValue];
    theRegion.center = self.coordinate;
    theRegion.span = theSpan;
  theRegion = [_mapView regionThatFits:theRegion];
    
    if (isnan(theRegion.span.latitudeDelta) || isnan(theRegion.span.longitudeDelta)) {
      
     //如果在这里操作,就会崩溃,抛出异常
    }
    else{
    
        [_mapView setRegion:theRegion];
    }

你可能感兴趣的:(MapView setRigion崩溃问题)