问题描述
我正在尝试将已保存的区域与另一个区域进行比较,无论该区域是否在该区域内。每当用户放大地图时,都会更改该区域;调用以下函数时:
func mapView(_ mapView:MKMapView,regionDidChangeAnimated动画: 布尔){
解决方法
您可以轻松定义自己的函数,以检查MKCoordinateRegion
是否包含另一个函数。一种方法是计算该区域的最小/最大纬度和经度,然后比较要比较的两个区域之间的所有4个末端。
extension MKCoordinateRegion {
var maxLongitude: CLLocationDegrees {
center.longitude + span.longitudeDelta / 2
}
var minLongitude: CLLocationDegrees {
center.longitude - span.longitudeDelta / 2
}
var maxLatitude: CLLocationDegrees {
center.latitude + span.latitudeDelta / 2
}
var minLatitude: CLLocationDegrees {
center.latitude - span.latitudeDelta / 2
}
func contains(_ other: MKCoordinateRegion) -> Bool {
maxLongitude >= other.maxLongitude && minLongitude <= other.minLongitude && maxLatitude >= other.maxLatitude && minLatitude <= other.minLatitude
}
}
let largerRegion = MKCoordinateRegion(MKMapRect(x: 50,y: 50,width: 100,height: 100))
let smallerRegion = MKCoordinateRegion(MKMapRect(x: 70,width: 30,height: 80))
let otherRegion = MKCoordinateRegion(MKMapRect(x: -100,y: 0,height: 80))
largerRegion.contains(smallerRegion) // true
largerRegion.contains(otherRegion) // false
smallerRegion.contains(otherRegion) // false