How to know whether MKMapView visibleMapRect contains a Coordinate?
Asked Answered
P

3

12

If I have a MKMapView and a CLLocationCoordinate2D how do you test whether the map's visible area contains the coordinate?

Preoccupancy answered 26/4, 2013 at 14:57 Comment(0)
M
33

The fastest way is to use the inbuilt Apple functions which will make this sort of thing super quick!

if(MKMapRectContainsPoint(mapView.visibleMapRect, MKMapPointForCoordinate(coordinate)))
{
    //Do stuff
}

Where coordinate is your CLLocation2D.

This will be much faster than working out coordinates with a bulk if statement. Reason is that Apple use a Quadtree and can do fast lookups for you.

Mirella answered 26/4, 2013 at 15:26 Comment(0)
N
6

Swift 3 compatible

If you frequently work with maps I suggest you to create an extension like this:

extension MKMapView {
    
    func contains(coordinate: CLLocationCoordinate2D) -> Bool {
        return MKMapRectContainsPoint(self.visibleMapRect, MKMapPointForCoordinate(coordinate))
    }
    
}

Then you can use wherever, for example:

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
    if mapView.contains(coordinate: mapView.centerCoordinate) {
       // do stuff
    }
}

In this way you keep the code:

  • more maintainable: if Apple decide to change its frameworks you will able to do a fast refactor changing code in a single point
  • more testable
  • more readable and clean
Natch answered 25/5, 2017 at 13:14 Comment(0)
L
1

my two cents for swift 5.1

  extension MKMapView {

      func contains(coordinate: CLLocationCoordinate2D) -> Bool {
        return self.visibleMapRect.contains(MKMapPoint(coordinate))
    }

 }
Lillis answered 21/11, 2019 at 11:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.