Creating MKMapRect from coordinates and using mapView.visibleMapRect

2.3k views Asked by At

I'm trying to see if some extents (max x, max y, min x, min y coordinates) I have are in the current visible map view.

I take my extents and create a MKMapRect:

MKMapPoint upperLeft = MKMapPointForCoordinate(CLLocationCoordinate2DMake([boundary.extents.maxY floatValue], [boundary.extents.minY floatValue]));
MKMapPoint lowerLeft = MKMapPointForCoordinate(CLLocationCoordinate2DMake([boundary.extents.minY floatValue], [boundary.extents.minY floatValue]));
MKMapPoint upperRight = MKMapPointForCoordinate(CLLocationCoordinate2DMake([boundary.extents.maxY floatValue], [boundary.extents.maxY floatValue]));

MKMapRect mapRect = MKMapRectMake(upperLeft.x, upperLeft.y, fabs(upperLeft.x - upperRight.x), fabs(upperLeft.y - lowerLeft.y));

Now I want to check if my 'mapRect' is in the mapView.visibleMapRect:

if (MKMapRectContainsRect(mapView.visibleMapRect, mapRect)) {
    // do some stuff
}

But my extents are never contained by the mapView.visibleMapRect when I know they should be.

If I replace the mapView.visibleMapRect with MKMapRectWorld, then it will contain my extents 'mapRect'.

Am I doing something wrong? is mapView.visibleMapRect not what I think it is (the viewable area on the screen)?

2

There are 2 answers

0
Padin215 On

D'oh!

The issue was that I used minY instead of minX.

MKMapPoint upperLeft = MKMapPointForCoordinate(CLLocationCoordinate2DMake([boundary.extents.maxY floatValue], [boundary.extents.**minX** floatValue]));
MKMapPoint lowerLeft = MKMapPointForCoordinate(CLLocationCoordinate2DMake([boundary.extents.minY floatValue], [boundary.extents.**minX** floatValue]));
MKMapPoint upperRight = MKMapPointForCoordinate(CLLocationCoordinate2DMake([boundary.extents.maxY floatValue], [boundary.extents.**maxX** floatValue]));
1
Jeff Ames On

mapView.visibleMapRect is exactly what you think it is, the map rect displayed by your map view. The problem is probably that the MKMapRectContainsRect function only tells you if one map rect is entirely contained (completely enclosed) in another. It's likely that you just want to use MKMapRectIntersectsRect which just tells you that part of your map rect is inside your mapView.visibleMapRect