Monday, November 9, 2009

MKMapView Category

I've been working with MapKit quite a bit the last few days as I finish the chapter on MapKit. I was surprised to find that the map view didn't have a method for telling you whether specific coordinates were currently being shown on screen. The map view has a method to tell you whether the user's current location is visible, but I couldn't find one to that indicated if any arbitrary coordinates were currently visible on screen.

This category rectifies that.

MKMapView-CoordsDisplay.h
#import <MapKit/MapKit.h>

@interface MKMapView(CoordsDisplay)
- (BOOL)coordinatesInRegion:(CLLocationCoordinate2D)coords;
@end


MKMapView-CoordsDisplay.m
#import "MKMapView-CoordsDisplay.h"

@implementation MKMapView(CoordsDisplay)
- (BOOL)coordinatesInRegion:(CLLocationCoordinate2D)coords
{
CLLocationDegrees leftDegrees = self.region.center.longitude - (self.region.span.longitudeDelta / 2.0);
CLLocationDegrees rightDegrees = self.region.center.longitude + (self.region.span.longitudeDelta / 2.0);
CLLocationDegrees bottomDegrees = self.region.center.latitude - (self.region.span.latitudeDelta / 2.0);
CLLocationDegrees topDegrees = self.region.center.latitude + (self.region.span.latitudeDelta / 2.0);

return leftDegrees <= coords.longitude && coords.longitude <= rightDegrees && bottomDegrees <= coords.latitude && coords.latitude <= topDegrees;
}

@end

No comments:

Post a Comment