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, 动画: true)
解决方案
这是计算适合所有注释边界的矩形的错误方法。
使用它,它将注释映射到它们的坐标,然后映射到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)
推荐阅读
- java - Camera.open() 为什么这行代码会使我的 android 应用程序崩溃?
- dart - Dart 中有 Goto 函数吗?
- javascript - 如何在循环中发出 XHR 请求并在带有随机名称的回调中处理答案?
- jquery - 未捕获的类型错误:$(...).magnificPopup 不是函数
- python - 如何使用 Python 通过 CAN 发送消息?
- javascript - Chrome 扩展上下文菜单äö 编码
- python - Python json.decoder.JSONDecodeError
- r - dplyr:使用 select_if() 进行条件列选择
- python-3.x - 子类无法从父类获取属性值
- python - 寻找方向以建立在线网络爬虫数据库