Mohamed ALOUANE
Mohamed ALOUANE

Reputation: 5407

How to determine if MKCoordinateRegion inside another MKCoordinateRegion

I am trying to compare a saved region with another region, whether it's inside of that region or not. The region is going to be changed each time the user zoom in on the map; when the function below is called:

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

Upvotes: 2

Views: 846

Answers (1)

David Pasztor
David Pasztor

Reputation: 54706

You can easily define your own function for checking if an MKCoordinateRegion contains another one. One way to do this is to calculate the min/max latitude and longitudes of the region, then compare all 4 extremities between the 2 regions you want to compare.

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

Upvotes: 4

Related Questions