' 快速错误,swift,mapkit,mkcoordinateregion"/>

首页 > 解决方案 > 如何修复此“无效区域”' 快速错误

问题描述

我想获取该区域,以便可以将注释放入其中。但我得到了未捕获的异常 '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, 动画: true)

标签: swiftmapkitmkcoordinateregion

解决方案


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

使用它,它将注释映射到它们的坐标,然后映射到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)

推荐阅读