如何确定 MKCoordinateRegion 是否在另一个 MKCoordinateRegion 内

How to determine if MKCoordinateRegion inside another MKCoordinateRegion

我正在尝试将保存的区域与另一个区域进行比较,无论它是否在该区域内。每次用户放大地图时,区域都会发生变化;当下面的函数被调用时:

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {

您可以轻松定义自己的函数来检查 MKCoordinateRegion 是否包含另一个函数。一种方法是计算该区域的 min/max 纬度和经度,然后比较您要比较的 2 个区域之间的所有 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, y: 50, width: 30, height: 80))
let otherRegion = MKCoordinateRegion(MKMapRect(x: -100, y: 0, width: 100, height: 80))

largerRegion.contains(smallerRegion) // true
largerRegion.contains(otherRegion) // false
smallerRegion.contains(otherRegion) // false