我正在使用MapKit,在启动应用程序时不时会出现以下错误。
'Invalid Region <center:nan, nan span:+180.00000000, +360.00000000>'
我用于设置区域的代码如下。
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
if (!self.initialLocation)
{
NSLog(@"Center is %f", userLocation.coordinate.longitude); // Debug
[self calculateLocationAddress]; // Reverse geolocating, does not create the error
self.initialLocation = userLocation.location;
MKCoordinateRegion region;
region.center = userLocation.coordinate;
// Region to show when app is loaded
region.span = MKCoordinateSpanMake(0.04, 0.04);
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];
}
}
该方法中的日志显示用户位置已设置,因为我一直在其中获取正确的值,即使它会因无效区域错误而崩溃。我还尝试过使用CLLocationCoordinate2DIsValid
来验证该区域,但出现了相同的错误。如上所述,这种错误是非常偶然的,不时出现。关于我可能做错了什么,有什么想法吗?
编辑:如果我打开故事板并在再次编译之前对其进行更改,错误几乎总是会消失。
我也遇到过同样的问题,通过下面的代码解决了这个问题。
if ( (region.center.latitude >= -90) && (region.center.latitude <= 90) && (region.center.longitude >= -180) && (region.center.longitude <= 180)) {
self.mapView.setRegion(region, animated: true)
}
else
{
print("Invalid region!")
}
快乐编码感谢
您可以使用CLLocationCoordinate2DIsValid代替
https://developer.apple.com/documentation/corelocation/1423806-cllocationcoordinate2disvalid