我想获取区域,以便可以在其中放入注释。但是我未捕获到异常'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),范围: MKCoordinateSpan(latitudeDelta:fabs(topLeftCoordinate.latitude- bottomRightCoordinate.latitude)* 2.0,经度Delta: fabs(bottomRightCoordinate.longitude-topLeftCoordinate.longitude)* 2.0))
region = mapView.regionThatFits(region)mapView.setRegion(region, 动画:true)
答案 0 :(得分:1)
这是计算适合所有注释范围的矩形的错误方法。
使用它,它将注释映射到其坐标,然后映射到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)