2

I tried to set visibleMapRect property of MKMapView object but result map rect is not the exact what I expected.

This is my code:

NSLog(@"current size %f %f", mapView.visibleMapRect.size.width, mapView.visibleMapRect.size.height);
NSLog(@"target size %f %f", newBounds.size.width, newBounds.size.height);
mapView.visibleMapRect = newBounds;
NSLog(@"new size %f %f", mapView.visibleMapRect.size.width, mapView.visibleMapRect.size.height);

And this is the result:

2013-01-15 19:21:25.440 MyApp[4216:14c03] current size 67108864.594672 46006272.643333
2013-01-15 19:21:25.441 MyApp[4216:14c03] target size 3066685.527175 2102356.690531
2013-01-15 19:21:25.442 MyApp[4216:14c03] new size 4194304.162631  2875392.126220

What kind of magic is this? And how can I set the precise visible rect to my map view?

Lloyd18
  • 1,679
  • 1
  • 18
  • 28
  • 2
    See http://stackoverflow.com/a/7419989/467105. Even though that question involves setting `region`, it also applies to setting `visibleMapRect`. –  Jan 16 '13 at 03:50

1 Answers1

1

Thanks to Anna Karenina's comment I found the answer. MKMapView setVisibleMapRect methods shows rect with maximum zoom level to fit input rect and show map tiles pixel per pixel to keep image looks crisp.

So I write this code to predict MKMapRect that will be shown for input MKMapRect.

- (MKMapRect)expectedMapRectForMapRect:(MKMapRect)mapRect inMapView:(MKMapView*)mapView
{
    CGFloat targetPointPerPixelRatio = MAX(MKMapRectGetWidth(mapRect) / CGRectGetWidth(mapView.bounds), MKMapRectGetHeight(mapRect) / CGRectGetHeight(mapView.bounds));
    CGFloat expextedPointPerPixelRatio = powf(2, ceilf(log2f(targetPointPerPixelRatio)));

    NSLog(@"expextedPointPerPixelRatio %f", expextedPointPerPixelRatio);
    MKMapRect expectedMapRect;
    expectedMapRect.size = MKMapSizeMake(CGRectGetWidth(mapView.bounds)*expextedPointPerPixelRatio, CGRectGetHeight(mapView.bounds)*expextedPointPerPixelRatio);
    expectedMapRect.origin = MKMapPointMake(MKMapRectGetMidX(mapRect) - expectedMapRect.size.width/2, MKMapRectGetMidY(mapRect) - expectedMapRect.size.height/2);

    expectedMapRect.origin.x = roundf(expectedMapRect.origin.x / expextedPointPerPixelRatio) * expextedPointPerPixelRatio;
    expectedMapRect.origin.y = roundf(expectedMapRect.origin.y / expextedPointPerPixelRatio) * expextedPointPerPixelRatio;
    return expectedMapRect;
}
Lloyd18
  • 1,679
  • 1
  • 18
  • 28