How to know whether MKMapView visibleMapRect contains a Coordinate?

时间秒杀一切 提交于 2019-12-02 23:38:24

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!