Как исправить эту ошибку «Недопустимая область <центр: -180.00000000, -180.00000000 span: nan, nan>» в быстром - PullRequest
1 голос
/ 10 мая 2019

Я бы хотел получить регион, чтобы в него помещались аннотации. Но я получил неперехваченное исключение NSInvalidArgumentException, причина: «Недопустимый регион». Итак, как я решу эту проблему, пожалуйста?

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 (центр: 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, долготаDelta: fabs (bottomRightCoordinate.longitude - topLeftCoordinate.longitude) * 2.0))

region = mapView.regionThatFits (region) mapView.setRegion (region, анимация: правда)

1 Ответ

1 голос
/ 10 мая 2019

Это неправильный способ вычисления прямоугольника, который соответствует границам всех аннотаций.

Используйте это, он отображает аннотации в их координаты, а затем в MKMapRect экземпляры.Функция reduce/union вычисляет размер прямоугольника

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

Или, намного проще (благодаря Sulthan)

let annotations = mapView.annotations.filter{!($0 is DriverAnnotation)}
mapView.showAnnotations(annotations, animated: true)
...