How to check if MKCoordinateRegion contains CLLocationCoordinate2D without using MKMapView? How to check if MKCoordinateRegion contains CLLocationCoordinate2D without using MKMapView? ios ios

How to check if MKCoordinateRegion contains CLLocationCoordinate2D without using MKMapView?


I'm posting this answer as the accepted solution is not valid in my opinion. This answer is also not perfect but it handles the case when coordinates wrap around 360 degrees boundaries, which is enough to be suitable in my situation.

+ (BOOL)coordinate:(CLLocationCoordinate2D)coord inRegion:(MKCoordinateRegion)region{    CLLocationCoordinate2D center = region.center;    MKCoordinateSpan span = region.span;    BOOL result = YES;    result &= cos((center.latitude - coord.latitude)*M_PI/180.0) > cos(span.latitudeDelta/2.0*M_PI/180.0);    result &= cos((center.longitude - coord.longitude)*M_PI/180.0) > cos(span.longitudeDelta/2.0*M_PI/180.0);    return result;}


You can convert your location to a point with MKMapPointForCoordinate, then use MKMapRectContainsPoint on the mapview's visibleMapRect. This is completely off the top of my head. Let me know if it works.


In case there is anybody else confused with latitudes and longitues, here is tested, working solution:

MKCoordinateRegion region = self.mapView.region;CLLocationCoordinate2D location = user.gpsposition.coordinate;CLLocationCoordinate2D center   = region.center;CLLocationCoordinate2D northWestCorner, southEastCorner;northWestCorner.latitude  = center.latitude  - (region.span.latitudeDelta  / 2.0);northWestCorner.longitude = center.longitude - (region.span.longitudeDelta / 2.0);southEastCorner.latitude  = center.latitude  + (region.span.latitudeDelta  / 2.0);southEastCorner.longitude = center.longitude + (region.span.longitudeDelta / 2.0);if (    location.latitude  >= northWestCorner.latitude &&     location.latitude  <= southEastCorner.latitude &&    location.longitude >= northWestCorner.longitude &&     location.longitude <= southEastCorner.longitude    ){    // User location (location) in the region - OK :-)    NSLog(@"Center (%f, %f) span (%f, %f) user: (%f, %f)| IN!", region.center.latitude, region.center.longitude, region.span.latitudeDelta, region.span.longitudeDelta, location.latitude, location.longitude);}else {    // User location (location) out of the region - NOT ok :-(    NSLog(@"Center (%f, %f) span (%f, %f) user: (%f, %f)| OUT!", region.center.latitude, region.center.longitude, region.span.latitudeDelta, region.span.longitudeDelta, location.latitude, location.longitude);}