如何修复 swift 中的 'Invalid Region <center:-180.00000000, -180.00000000 span:nan, nan>' 错误

How to fix this 'Invalid Region <center:-180.00000000, -180.00000000 span:nan, nan>' error in swift

我想获取该区域,以便在其中放置注释。但是我得到了未捕获的异常 'NSInvalidArgumentException',原因:'Invalid Region '。请问云我是怎么解决这个问题的?

var topLeftCoordinate = CLLocationCoordinate2D(latitude: -90, longitude: 180)
var bottomRightCoordinate = CLLocationCoordinate2D(latitude: 90, longitude: -180)

for annotation in mapView.annotations where !annotation.isKind(of: DriverAnnotation.self){
            topLeftCoordinate.longitude = fmin(topLeftCoordinate.longitude, annotation.coordinate.longitude)
            topLeftCoordinate.latitude = fmax(topLeftCoordinate.latitude, annotation.coordinate.latitude)
            bottomRightCoordinate.longitude = fmin(bottomRightCoordinate.longitude, annotation.coordinate.longitude)
            bottomRightCoordinate.latitude = fmax(bottomRightCoordinate.latitude, annotation.coordinate.latitude)
        }

var region = MKCoordinateRegion(center: CLLocationCoordinate2DMake(topLeftCoordinate.latitude - (topLeftCoordinate.latitude - bottomRightCoordinate.latitude) * 0.5, topLeftCoordinate.longitude + (bottomRightCoordinate.longitude - topLeftCoordinate.longitude) * 0.5), span: MKCoordinateSpan(latitudeDelta: fabs(topLeftCoordinate.latitude - bottomRightCoordinate.latitude) * 2.0, longitudeDelta: fabs(bottomRightCoordinate.longitude - topLeftCoordinate.longitude) * 2.0))

region = mapView.regionThatFits(region) mapView.setRegion(region, animated: true)

这是计算适合所有注释边界的矩形的错误方法。

使用它,它将注释映射到它们的坐标,然后映射到 MKMapRect 个实例。 reduce/union函数计算rect的大小

let coordinates = mapView.annotations.lazy.filter{!([=10=] is DriverAnnotation)}.map{ [=10=].coordinate }
let rects = coordinates.map { MKMapRect(origin: MKMapPoint([=10=]), size: MKMapSize()) }
let mapRect = rects.reduce(MKMapRect.null) { [=10=].union() }
mapView.setVisibleMapRect(mapRect, animated: true)

或者,更简单(感谢 Sulthan)

let annotations = mapView.annotations.filter{!([=11=] is DriverAnnotation)}
mapView.showAnnotations(annotations, animated: true)