Display MKMapViewAnnotations within a map view's visible rect - ios

I'm displaying an MKMapView inside a Path-style parallax table view header. To create the effect, the mapView bounds is larger than the area visible to the user. I need to set the map view region such that all the map's annotations are contained within the visible rect of MKMapView. What's the best way to do this?
Edit for clarity: Here's a use-case. The mapView size is 320 x 380. The visible area, however, is defined by the rect (0.0, 20.0, 320.0, 100.0). I need to set the region such that all the annotations appear in this rect within the mapView.

Setting the map region so that all annotations are contained in a certain part of an MKMapView can be done in three steps. Input are the mapView and the annotationsFrame.
Calculate an MKMapRect mapRect that contains all annotations.
Calculate the padding insets from mapView.bounds and annotationsFrame.
Call -setVisibleMapRect:edgePadding:animated: on the map view.
Below is a screen shot of a test. The red overlay shows the annotationsFrame.
Here is the code. Beware: It's all in one method to simplify adding it to your code, and it is not tested for edge cases like passing in n annotations with the same coordinate, or having the annotations so far apart that the map would have to get zoomed out too much, or having coordinates that span the edge of the map at +/-180 degrees longitude.
- (void)zoomAnnotationsOnMapView:(MKMapView *)mapView toFrame:(CGRect)annotationsFrame animated:(BOOL)animated
{
if (_mapView.annotations.count < 2) return;
// Step 1: make an MKMapRect that contains all the annotations
NSArray *annotations = _mapView.annotations;
id <MKAnnotation> firstAnnotation = [annotations objectAtIndex:0];
MKMapPoint minPoint = MKMapPointForCoordinate(firstAnnotation.coordinate);
MKMapPoint maxPoint = minPoint;
for (id <MKAnnotation> annotation in annotations) {
MKMapPoint point = MKMapPointForCoordinate(annotation.coordinate);
if (point.x < minPoint.x) minPoint.x = point.x;
if (point.y < minPoint.y) minPoint.y = point.y;
if (point.x > maxPoint.x) maxPoint.x = point.x;
if (point.y > maxPoint.y) maxPoint.y = point.y;
}
MKMapRect mapRect = MKMapRectMake(minPoint.x, minPoint.y, maxPoint.x - minPoint.x, maxPoint.y - minPoint.y);
// Step 2: Calculate the edge padding
UIEdgeInsets edgePadding = UIEdgeInsetsMake(
CGRectGetMinY(annotationsFrame),
CGRectGetMinX(annotationsFrame),
CGRectGetMaxY(mapBounds) - CGRectGetMaxY(annotationsFrame),
CGRectGetMaxX(mapBounds) - CGRectGetMaxX(annotationsFrame)
);
// Step 3: Set the map rect
[mapView setVisibleMapRect:mapRect edgePadding:edgePadding animated:animated];
}
If you go for a perfect placement (and who doesn't), here are three things to consider:
The code assures that all the coordinates are in the annotationsFrame, but the annotations themselves may be outside. To prevent that, simply use more padding. For example, if your annotations are 20x20 and centered on the coordinate, use 10 more padding on all sides.
Below iOS 7, the map was not zooming to the perfect zoom scale, but to the next tile size (power of two). So there will be more space around the annotations than needed, just as shown on the screenshot.
On iOS 7, the map view will not only zoom perfectly, but automatically care about the status bar. To make the calculation correct, you need to subtract the status bar height from the top padding on iOS 7.

Starting from iOS 7.0, this can be easily achieved with showAnnotations.
Swift:
mapView.showAnnotations(mapView.annotations, animated: true)
Objective-C:
[mapView showAnnotations:mapView.annotations animated:YES];
The above statement will adjust the map view's visible rect in order to display all annotations.

You first need to add the annotations:
(of course this is after you already have a list of annotations)
Swift4:
self.mapView.addAnnotations(annotations)
let currentView = mapView.visibleMapRect
mapView.annotations(in: currentView)
You can use the currentView constant or directly place the MKMapRect as such: Below: (.visibleMapRect returns:
"The area currently displayed by the map view."
mapView.annotations(in: mapView.visibleMapRect)

I found an easier way without calculating is let the map view calculate it, then we adjust the edges.
//1: Show all annotation on the map view, but without animation
self.mapView.showAnnotations(self.mapView.annotations, animated: false)
//2: Get the current visible map rect
let currentMapRect = self.mapView.visibleMapRect
//3: Create the edges inset that you want the map view to show all annotation within
let padding = UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100)
//4: Set current map rect but with new padding, also set animation to true to see effect
self.mapView.setVisibleMapRect(currentMapRect, edgePadding: padding, animated: true)

If you're prepared to approximate the calculations you can do it using some clever scaling.
Your target area is 80 tall out of a mapView that is 380. Therefore you want a region that is 4.75x taller than the region calculated to fit your annotations. (0.25 extra above and 3.5 extra below).
First you need to get a region (or maprect, what ever you prefer working in) and make it the same proportions as your target viewable area. This is because a really wide and short region would not be touching the top and bottom of the viewable area and therefore multiplying its height would not make something that touched the top and bottom of your map view. So if viewable_height/viewable_width > annotations_height/annotations_width you should set the annotations_height to annotations_width * (viewable_height/viewable_width).
With that you then add 25% on to the north of the annotations box and 350% on to the south. You can do this by moving the center 212.5% (of the current height) south and increasing the vertical span by 475%.
Now, all of this is an approximation given that the world is sphere and we're not looking at a planar projection (i.e. 1 degree of latitude near the equator is drawn smaller than 1 degree near the poles). But if you wally want to be accurate you could look into scaling the numbers according to latitude and such. If you're only dealing with annotations on a city-sized scale you'll probably be ok.
Hope that helps.

if you want to find the annotations that are in a given rect:
- (NSArray*)allAnnotationsInMapRect:(MKMapRect)mapRect {
NSMutableArray *annotationsInRect = [NSMutableArray array];
for(id<MKAnnotation *ann in self.allAnnotations) {
MKMapPoint pt = MKMapPointForCoordinate(ann.coordinate);
if(MKMapRectContainsPoint(mapRect, pt)) {
[annotationsInRect addObject:ann];
}
}
return annotationsInRect;
}
and to assure the annotation VIEWS are in the rect, get the region for the annotations,
then walk through them and get each view's bounds see if the bounds fit inside the visibleRect of the map and if not modify the region!
~~ like this:
- (void)assureAnnotationViewsAreVisible:(NSArray*)annotations originalRegion:(MKCoordinateRegion)originalRegion {
CGFloat smallestX = MAXFLOAT;
CGFloat smallestY = MAXFLOAT;
CGFloat biggestX = -100;
CGFloat biggestY = -100;
//NSLog(#"---: %d", annotations.count);
for(id<MKAnnotation> *annotation in annotations) {
UIView *annotationView = [self.mapView viewForAnnotation:v];
CGRect annotationViewFrame = annotationView.bounds;
annotationViewFrame.origin = [self.mapView convertCoordinate:annotationView.coordinate toPointToView:self.mapView];
annotationViewFrame.origin = CGPointMake(annotationViewFrame.origin.x-annotationViewFrame.size.width/2,
annotationViewFrame.origin.y-annotationViewFrame.size.height);
smallestX = MIN(annotationViewFrame.origin.x, smallestX);
smallestY = MIN(annotationViewFrame.origin.y, smallestY);
biggestX = MAX(annotationViewFrame.origin.x+annotationViewFrame.size.width, biggestX);
biggestY = MAX(annotationViewFrame.origin.y+annotationViewFrame.size.height, biggestY);
}
//NSLog(#"---");
CGRect bounds = self.mapView.bounds;
if(smallestX < bounds.origin.x || smallestY < bounds.origin.y || biggestX > bounds.origin.x+bounds.size.width || biggestY > bounds.origin.y+bounds.size.height) {
CGRect neededRect = bounds;
neededRect.origin = CGPointMake(MIN(bounds.origin.x, smallestX), MIN(bounds.origin.y, smallestY));
neededRect.size = CGSizeMake(MAX(bounds.size.width, biggestX), MAX(bounds.size.height, biggestY));
MKCoordinateRegion neededRegion = [self.mapView convertRect:neededRect toRegionFromView:self.mapView];
_ignoreRegionChange = YES;
[self.mapView setRegion:originalRegion animated:NO];
_ignoreRegionChange = NO;
[self.mapView setRegion:neededRegion animated:YES];
}
else {
MKCoordinateRegion currentRegion = self.mapView.region;
_ignoreRegionChange = YES;
[self.mapView setRegion:originalRegion animated:NO];
_ignoreRegionChange = NO;
[self.mapView setRegion:currentRegion animated:YES];
}
}

Try to get from all your annotation edges value (max and min) for lan and lon.
Define this value on the beginning:
static float maxLat = FLT_MIN;
static float maxLon = FLT_MIN;
static float minLat = FLT_MAX;
static float minLon = FLT_MAX;
and then use this function to calculate span and region:
- (void) zoomAndFit {
for(int i = 0; i < [self.points count]; i++) {
PRPlaceModel *place = [self.points objectAtIndex:i];
CLLocationCoordinate2D location;
location.latitude = [place.lat floatValue];
location.longitude = [place.lon floatValue];
minLat = MIN(minLat, location.latitude);
minLon = MIN(minLon, location.longitude);
maxLat = MAX(maxLat, location.latitude);
maxLon = MAX(maxLon, location.longitude);
}
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 1.2*(maxLat - minLat);
span.longitudeDelta = 1.2*(maxLon - minLon);
CLLocationCoordinate2D location;
location.latitude = (minLat + maxLat)/2;
location.longitude = (minLon + maxLon)/2;
region.span=span;
region.center=location;
[self.mapView setRegion:region animated:TRUE];
[self.mapView regionThatFits:region];
}
And use it in viewDidLoad method:
-(void)viewDidLoad
{
[super viewDidLoad];
[self zoomAndFit];
}

Related

How to set the zoom level of the MKMap view making MKCircle(varying radius) visible?

My map view contains one circle which covers many pinpoints with one center point.Whenever the user clicks a button the map should be zoomed in such a level the circle is visible.The map should not be zoomed more or less it should show exact circle.When user logs out then circle will have new radius in next login.How to calculate the appropriate zoom level.
My code:
-(void)showCircle{
//calculate new radius
long radius=[self calculateRadius];
MKCircle *circle= [[MKCircle alloc]init];
circle = [MKCircle circleWithCenterCoordinate:CLLocationCoordinate2DMake([groupLat floatValue], [groupLon floatValue]) radius:radius];
[myMapView addOverlay:circle];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake([groupLat floatValue], [groupLon floatValue]), 800, 800);
MKCoordinateSpan span;
//calculate zoom level
double radius=[circle radius]);
double rad = radius + radius / 2;
double scale = rad / 500;
zoomLevel=(16 - log(scale) / log(2));
region.span.latitudeDelta =zoomLevel;
region.span.longitudeDelta =zoomLevel;
[myMapView setRegion:region animated:YES];
}
Thank you in advance!
You can try : mapRectThatFits(:) or mapRectThatFits(:edgePadding:)
Something like this, maybe, to zoom the map according to your circle :
myMapView.visibleMapRect = [myMapView mapRectThatFits:circle.boundingMapRect];
Hope this helps you :)

MKMapView zoom to fit annotations while locking center

I'm trying to zoom to fit annotations on a map while locking the center and providing some insets.
- (void)fitAnnotations:(NSArray *)annotations edgeInsets:(UIEdgeInsets)insets
{
CLLocationCoordinate2D originalCenter = self.centerCoordinate;
MKMapRect mapRect = MKMapRectNull;
for (id<MKAnnotation> annotation in annotations) {
MKMapPoint p = MKMapPointForCoordinate([annotation coordinate]);
mapRect = MKMapRectUnion(mapRect, MKMapRectMake(p.x, p.y, 0, 0));
}
mapRect = [self mapRectThatFits:mapRect edgePadding:insets];
MKCoordinateRegion mapRegion = MKCoordinateRegionForMapRect(mapRect);
// we now try to go back to the original center, while increasing the span by neccessary amount
MKCoordinateSpan centeringDelta = MKCoordinateSpanMake(fabs(mapRegion.center.latitude - originalCenter.latitude), fabs(mapRegion.center.longitude - originalCenter.longitude));
mapRegion.center = originalCenter;
mapRegion.span.latitudeDelta += centeringDelta.latitudeDelta * 2.0;
mapRegion.span.longitudeDelta += centeringDelta.longitudeDelta * 2.0;
mapRegion = [self regionThatFits:mapRegion];
[self setRegion:mapRegion animated:YES];
}
The first part of the code here works as expected: it zooms to fit while respecting the insets. However, it shifts the center.
I try to re-adjust the center after that, but it fails. I'm not sure if my math on the re-centering is correct.
The first part of your code that calculates the bounding map rect that fits the annotations is OK.
Only the adjustment of that "minimal" map rect so that the "locked" center is actually in the center needs to be corrected.
The main problem, I believe, is that the code in the question is adjusting the span to both re-center the region and account for the insets after calling mapRectThatFits: (which will itself already give a slightly modified version of the rect you actually requested).
Instead, your code should only calculate the actual, minimal rect it wants and then finally call setVisibleMapRect:edgePadding:animated: and let the map view figure out both the "rect that fits" and the insets.
Please try the following:
- (void)fitAnnotations:(NSArray *)annotations edgeInsets:(UIEdgeInsets)insets
{
MKMapPoint centerMapPoint = MKMapPointForCoordinate(originalCenter);
//--- First create minimal bounding map rect to tightly fit annotations...
MKMapRect minimalMapRect = MKMapRectNull;
for (id<MKAnnotation> annotation in annotations) {
MKMapPoint annMapPoint = MKMapPointForCoordinate(annotation.coordinate);
minimalMapRect = MKMapRectUnion(minimalMapRect, MKMapRectMake(annMapPoint.x, annMapPoint.y, 0, 0));
}
//--- Now create adjusted map rect so center coordinate is in the center...
//distance of desired center from minimal left edge...
double centerXOffset = centerMapPoint.x - minimalMapRect.origin.x;
//raw amount width needs to be adjusted to get center in center...
//negative/positive indicates whether center is in left/right half
double widthOffset = 2.0 * centerXOffset - minimalMapRect.size.width;
//add absolute value of raw width offset to minimal width...
double adjustedWidth = minimalMapRect.size.width + fabs(widthOffset);
//distance of desired center from minimal top edge...
double centerYOffset = centerMapPoint.y - minimalMapRect.origin.y;
//raw amount height needs to be adjusted to get center in center...
//negative/positive indicates whether center is in top/bottom half
double heightOffset = 2.0 * centerYOffset - minimalMapRect.size.height;
//add absolute value of raw height offset to minimal height...
double adjustedHeight = minimalMapRect.size.height + fabs(heightOffset);
//adjust origin if necessary (if center is in top/left half)...
MKMapPoint adjustedOrigin = minimalMapRect.origin;
if ((centerXOffset / minimalMapRect.size.width) < 0.5)
{
adjustedOrigin.x = adjustedOrigin.x + widthOffset;
}
if ((centerYOffset / minimalMapRect.size.height) < 0.5)
{
adjustedOrigin.y = adjustedOrigin.y + heightOffset;
}
//create adjusted MKMapRect...
MKMapRect adjustedMapRect = MKMapRectMake(adjustedOrigin.x, adjustedOrigin.y, adjustedWidth, adjustedHeight);
//--- Apply the adjusted map rect with insets to map view...
[mapView setVisibleMapRect:adjustedMapRect edgePadding:insets animated:YES];
}
Try something like this, where you use your calculated mapRect to create the new region with your originalCenter via the MKCoordinateRegionMake method
MKCoordinateRegion mapRegion = MKCoordinateRegionForMapRect(mapRect);
mapRegion = MKCoordinateRegionMake(originalCenter, mapRegion.span);
mapView.region = mapRegion;
Try this.
MKMapPoint center = MKMapPointForCoordinate(self.mapView.centerCoordinate);
double maxX = 0;
double maxY = 0;
for (MKPointAnnotation *a in self.mapView.annotations)
{
MKMapPoint p = MKMapPointForCoordinate(a.coordinate);
double deltaX = fabs(center.x - p.x);
double deltaY = fabs(center.y - p.y);
maxX = MAX(maxX, deltaX);
maxY = MAX(maxY, deltaY);
}
MKMapRect rect = MKMapRectMake(center.x - maxX, center.y - maxY, maxX * 2, maxY * 2);
rect = [self.mapView mapRectThatFits:rect edgePadding:UIEdgeInsetsMake(20, 20, 20, 20)];
[self.mapView setVisibleMapRect:rect animated:1];
#moby I am thinking of a different approach. How about taking the maps centre location as you already did. Now calculate distance to each annotation from this centre coordinate till you find the longest annotation (say 'requiredDistance' ).
Get a new map rect with all your annotations plotted with same centre using below code:
MKCircle *circleLine = [MKCircle circleWithCenterCoordinate:self.centerCoordinate radius:requiredDistance];
[self.mapView setVisibleMapRect:circleLine.boundingMapRect];
Coming to your insets what ever insets you wanted to apply should be applied to your 'requiredDistace' variable in such a way that your 'requiredDistance' variable has a value always greater than or equal to the distance between your centre coordinate and your longest annotation to make sure all the annotations are always visible.

Fit Annotations on MKMapView part

I got MKMapView and a number of annotations on it. I use next code for displaying all annotations:
NSArray *coordinates = [self.mapView valueForKeyPath:#"annotations.coordinate"];
CLLocationCoordinate2D maxCoord = {-90.0f, -180.0f};
CLLocationCoordinate2D minCoord = {90.0f, 180.0f};
for(NSValue *value in coordinates) {
CLLocationCoordinate2D coord = {0.0f, 0.0f};
[value getValue:&coord];
if(coord.longitude > maxCoord.longitude) {
maxCoord.longitude = coord.longitude;
}
if(coord.latitude > maxCoord.latitude) {
maxCoord.latitude = coord.latitude;
}
if(coord.longitude < minCoord.longitude) {
minCoord.longitude = coord.longitude;
}
if(coord.latitude < minCoord.latitude) {
minCoord.latitude = coord.latitude;
}
}
MKCoordinateRegion region = {{0.0f, 0.0f}, {0.0f, 0.0f}};
region.center.longitude = (minCoord.longitude + maxCoord.longitude) / 2.0;
region.center.latitude = (minCoord.latitude + maxCoord.latitude) / 2.0;
region.span.longitudeDelta = (maxCoord.longitude - minCoord.longitude) * 1.5;
region.span.latitudeDelta = (maxCoord.latitude - minCoord.latitude) * 1.5;
[self.mapView setRegion:region animated:YES];
This code centers all annotations - perfect. But what if I want to fit annotations, lets say, on right half part of map. Is there any way to do that?
Here how it's now:
Here what I want to achieve:
If your target area is always to the left or right (i.e. still allowing full height) then it is very easy, you just need to work out the maths for your region's boundaries.
Let's assume you want the pins to be in the right-hand quarter of the page. This would mean you need to tell the map to view a region 4x (targetspan/currentspan) bigger than the pin region and with the middle of that region being shifted left by 1.5x ((targetspan-currentspan)/2)the width of the region. (I'm going to sat latitude is from 0 to 1 but really you just use what ever you have calculated already)
Imagine the view being divided into four vertical strips, there would be 5 lines. The left edge of the screen is 0, the next line is 1, the middle is 2, the next is 3 and the last is 4.
You want your pins to be between lines 3 and 4, meaning the longitude span you calculated above is 1 unit wide and the center.longitude is at 3.5.
You have a region that is ((3.5,0.5), (1,1)) and you need to tell your map to zoom to the region ((2,0.5),(4,1)). So, get the longitudeDelta, multiply it by 1.5 and subtract that from the center.longitude, that is your new target center.longitude. Then multiply the longitudeDelta by 4 and that is your new longitudeDelta.
You can do something similar with latitude on a small scale, but on a large scale the calculations ned to take into account the map projection which means the pixels near the equator represent more land than those near the poles.

How to adjust region to fit custom annotation callout that have just appeared?

I use my custom subclass of MKAnnotationView. In mapView:didSelectAnnotationView: method of my Map's delegate I call the method of this class, which adds UIImageView with an image as a subview - it serves as my custom annotation callout.
When using default MKPinAnnotationView map does automatically adjust map region to display the annotation callout that have just appeared. How can I implement this behavior using custom MKAnnotationView subclass?
Current solution
I've crafted demo project having the stuff discussed below implemented: see there
AdjustRegionToFitAnnotationCallout project.
The latest iOS7 changes in how Map Kit's MKMapView renders map annotations made me to revisit this problem. I've made more accurate thinking about it and come up with much, very much better solution. I will leave the previous solution at the bottom of this answer, but remember - I was so wrong when I did it that way.
First of all we will need a helper CGRectTransformToContainRect() that expands a given CGRect to contain another CGRect.
Note: it's behavior is different from what CGRectUnion() does - CGRectUnion() returns just the smallest CGRect containing both CGRects, whereas the following helper allows parallel movement i.e. CGRectTransformToContainRect(CGRectMake(0, 0, 100, 100), CGRectMake(50, 50, 100, 100)) equals (CGRect){50, 50, 100, 100} and not (CGRect){0, 0, 150, 150} like CGRectUnion() does it. This behavior is exactly what we need when we want to have only adjusts using parallel movements and want to avoid map's zooming.
static inline CGRect CGRectTransformToContainRect(CGRect rectToTransform, CGRect rectToContain) {
CGFloat diff;
CGRect transformedRect = rectToTransform;
// Transformed rect dimensions should encompass the dimensions of both rects
transformedRect.size.width = MAX(CGRectGetWidth(rectToTransform), CGRectGetWidth(rectToContain));
transformedRect.size.height = MAX(CGRectGetHeight(rectToTransform), CGRectGetHeight(rectToContain));
// Comparing max X borders of both rects, adjust if
if ((diff = CGRectGetMaxX(rectToContain) - CGRectGetMaxX(transformedRect)) > 0) {
transformedRect.origin.x += diff;
}
// Comparing min X borders of both rects, adjust if
else if ((diff = CGRectGetMinX(transformedRect) - CGRectGetMinX(rectToContain)) > 0) {
transformedRect.origin.x -= diff;
}
// Comparing max Y borders of both rects, adjust if
if ((diff = CGRectGetMaxY(rectToContain) - CGRectGetMaxY(transformedRect)) > 0) {
transformedRect.origin.y += diff;
}
// Comparing min Y borders of both rects, adjust if
else if ((diff = CGRectGetMinY(transformedRect) - CGRectGetMinY(rectToContain)) > 0) {
transformedRect.origin.y -= diff;
}
return transformedRect;
}
Adjust method wrapped into an Objective-C category MKMapView(Extensions):
#implementation MKMapView (Extensions)
- (void)adjustToContainRect:(CGRect)rect usingReferenceView:(UIView *)referenceView animated:(BOOL)animated {
// I just like this assert here
NSParameterAssert(referenceView);
CGRect visibleRect = [self convertRegion:self.region toRectToView:self];
// We convert our annotation from its own coordinate system to a coodinate system of a map's top view, so we can compare it with the bounds of the map itself
CGRect annotationRect = [self convertRect:rect fromView:referenceView.superview];
// Fatten the area occupied by your annotation if you want to have a margin after adjustment
CGFloat additionalMargin = 2;
adjustedRect.origin.x -= additionalMargin;
adjustedRect.origin.y -= additionalMargin;
adjustedRect.size.width += additionalMargin * 2;
adjustedRect.size.height += additionalMargin * 2;
// This is the magic: if the map must expand its bounds to contain annotation, it will do this
CGRect adjustedRect = CGRectTransformToContainRect(visibleRect, annotationRect);
// Now we just convert adjusted rect to a coordinate region
MKCoordinateRegion adjustedRegion = [self convertRect:adjustedRect toRegionFromView:self];
// Trivial regionThatFits: sugar and final setRegion:animated: call
[self setRegion:[self regionThatFits:adjustedRegion] animated:animated];
}
#end
Now the controller and views:
#interface AnnotationView : MKAnnotationView
#property AnnotationCalloutView *calloutView;
#property (readonly) CGRect annotationViewWithCalloutViewFrame;
#end
#implementation AnnotationView
- (void)showCalloutBubble {
// This is a code where you create your custom annotation callout view
// add add it using -[self addSubview:]
// At the end of this method a callout view should be displayed.
}
- (CGRect)annotationViewWithCalloutViewFrame {
// Here you should adjust your annotation frame so it match itself in the moment when annotation callout is displayed and ...
return CGRectOfAdjustedAnnotation; // ...
}
#end
When AnnotationView-classed annotation is selected on map, it adds its calloutView as a subview, so custom annotation callout view is displayed. It is done using MKMapViewDelegate's method:
- (void)mapView:(MapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
// AnnotationPresenter is just a class that contains information to be displayed on callout annotation view
if ([view.annotation isKindOfClass:[AnnotationPresenter class]]) {
// Hide another annotation if it is shown
if (mapView.selectedAnnotationView != nil && [mapView.selectedAnnotationView isKindOfClass:[AnnotationView class]] && mapView.selectedAnnotationView != view) {
[mapView.selectedAnnotationView hideCalloutBubble];
}
mapView.selectedAnnotationView = view;
annotationView *annotationView = (annotationView *)view;
// This just adds *calloutView* as a subview
[annotationView showCalloutBubble];
[mapView adjustToContainRect:annotationView.annotationViewWithCalloutViewFrame usingReferenceView:annotationView animated:NO];
}
}
Of course your implementation may be different from what I've described here (mine is!). The most important part of above code is of course the [MKMapView adjustToContainRect:usingReferenceView:animated: method. Now I am really satisfied with the current solution and my understanding of this (and some related) problem. If you need any comments about the solution above, feel free to contact me (see profile).
The following Apple docs are very useful to understand what is going on in methods like -[MKMapView convertRect:fromView:]:
http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKMapView_Class/MKMapView/MKMapView.html
http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MapKitDataTypesReference/Reference/reference.html
http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MapKitFunctionsReference/Reference/reference.html
Also the first 10-15 minutes of WWDC 2013 session "What’s New in Map Kit" (#304) are very good to watch to have an excellent quick demo of the whole "Map with annotations" setup done by Apple engineer.
Initial solution (Does not work in iOS7, do not use it, use the solution above instead)
Somehow I forgot to answer my question at a time. Here is the complete solution I use nowadays (edited slightly for readability):
First of all a bit of map logic to be encapsulated somewhere in helpers file like MapKit+Helpers.h
typedef struct {
CLLocationDegrees top;
CLLocationDegrees bottom;
} MKLatitudeEdgedSpan;
typedef struct {
CLLocationDegrees left;
CLLocationDegrees right;
} MKLongitudeEdgedSpan;
typedef struct {
MKLatitudeEdgedSpan latitude;
MKLongitudeEdgedSpan longitude;
} MKEdgedRegion;
MKEdgedRegion MKEdgedRegionFromCoordinateRegion(MKCoordinateRegion region) {
MKEdgedRegion edgedRegion;
float latitude = region.center.latitude;
float longitude = region.center.longitude;
float latitudeDelta = region.span.latitudeDelta;
float longitudeDelta = region.span.longitudeDelta;
edgedRegion.longitude.left = longitude - longitudeDelta / 2;
edgedRegion.longitude.right = longitude + longitudeDelta / 2;
edgedRegion.latitude.top = latitude + latitudeDelta / 2;
edgedRegion.latitude.bottom = latitude - latitudeDelta / 2;
return edgedRegion;
}
Like MKCoordinateRegion (center coordinate + spans), MKEdgedRegion is just a way to define a region but using coordinates of its edges instead.
MKEdgedRegionFromCoordinateRegion() is a self-explanatory converter-method.
Suppose we have the following class for our annotations, containing its callout as a subview.
#interface AnnotationView : MKAnnotationView
#property AnnotationCalloutView *calloutView;
#end
When AnnotationView-classed annotation is selected on map, it adds its calloutView as a subview, so custom annotation callout view is displayed. It is done using MKMapViewDelegate's method:
- (void)mapView:(MapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
// AnnotationPresenter is just a class that contains information to be displayed on callout annotation view
if ([view.annotation isKindOfClass:[AnnotationPresenter class]]) {
// Hide another annotation if it is shown
if (mapView.selectedAnnotationView != nil && [mapView.selectedAnnotationView isKindOfClass:[AnnotationView class]] && mapView.selectedAnnotationView != view) {
[mapView.selectedAnnotationView hideCalloutBubble];
}
mapView.selectedAnnotationView = view;
annotationView *annotationView = (annotationView *)view;
// This just adds *calloutView* as a subview
[annotationView showCalloutBubble];
/* Here the trickiest piece of code goes */
/* 1. We capture _annotation's (not callout's)_ frame in its superview's (map's!) coordinate system resulting in something like (CGRect){4910547.000000, 2967852.000000, 23.000000, 28.000000} The .origin.x and .origin.y are especially important! */
CGRect annotationFrame = annotationView.frame;
/* 2. Now we need to perform an adjustment, so our frame would correspond to the annotation view's _callout view subview_ that it holds. */
annotationFrame.origin.x = annotationFrame.origin.x + ANNOTATION_CALLOUT_TRIANLE_HALF; // Mine callout view has small x offset - you should choose yours!
annotationFrame.origin.y = annotationFrame.origin.y - ANNOTATION_CALLOUT_HEIGHT / 2; // Again my custom offset.
annotationFrame.size = placeAnnotationView.calloutView.frame.size; // We can grab calloutView size directly because in its case we don't care about the coordinate system.
MKCoordinateRegion mapRegion = mapView.region;
/* 3. This was a long run before I did stop to try to pass mapView.view as an argument to _toRegionFromView_. */
/* annotationView.superView is very important - it gives us the same coordinate system that annotationFrame.origin is based. */
MKCoordinateRegion annotationRegion = [mapView convertRect:annotationFrame toRegionFromView:annotationView.superview];
/* I hope that the following MKEdgedRegion magic is self-explanatory */
MKEdgedRegion mapEdgedRegion = MKEdgedRegionFromCoordinateRegion(mapRegion);
MKEdgedRegion annotationEdgedRegion = MKEdgedRegionFromCoordinateRegion(annotationRegion);
float diff;
if ((diff = (annotationEdgedRegion.longitude.left - mapEdgedRegion.longitude.left)) < 0 ||
(diff = (annotationEdgedRegion.longitude.right - mapEdgedRegion.longitude.right)) > 0)
mapRegion.center.longitude += diff;
if ((diff = (annotationEdgedRegion.latitude.bottom - mapEdgedRegion.latitude.bottom)) < 0 ||
(diff = (annotationEdgedRegion.latitude.top - mapEdgedRegion.latitude.top)) > 0)
mapRegion.center.latitude += diff;
mapView.region = mapRegion;
}
}
I was looking for a similar solution, to fit a route and a callout in the visible rectangle of the screen. I tried some solutions but finally ended up just with setting enough padding on setVisibleMapRect:edgePadding:animated:. May not be as sophisticated, but basically does what I needed.
MKMapRect routeMapRect = myRoute.polyline.boundingMapRect;
CGFloat padding = myCallout.bounds.width / 2.0;
[myMapView setVisibleMapRect: routeMapRect edgePadding:UIEdgeInsetsMake(padding, padding, padding, padding) animated:YES];
Of course this can be way more optimized, e.g. with detecting on which side you actually need the padding and setting a smaller one on the other sides. But you get the idea.

How to fit a certain bounds consisting of NE and SW coordinates into the visible map view?

I need to fit a certain bounds within a map. I get the bounds from calling the google geocoder and reading the viewport property which looks like:
{
northeast = {
lat = "30.4212235";
lng = "-97.486942";
};
southwest = {
lat = "30.1128403";
lng = "-97.99917959999999";
};
}
I then convert these into CLLocationCoordinate2D
NSDictionary *viewport = [[[results objectAtIndex:0] objectForKey:#"geometry"]
objectForKey:#"viewport"];
NSDictionary *NEDictionary = [viewport objectForKey:#"northeast"];
NSDictionary *SWDictionary = [viewport objectForKey:#"southwest"];
CLLocationCoordinate2D SWCoordinate =
CLLocationCoordinate2DMake(
[[SWDictionary objectForKey:#"lat"] floatValue],
[[SWDictionary objectForKey:#"lng"] floatValue]
);
CLLocationCoordinate2D NECoordinate =
CLLocationCoordinate2DMake(
[[NEDictionary objectForKey:#"lat"] floatValue],
[[NEDictionary objectForKey:#"lng"] floatValue]
);
I know I need to generate a MKMapRect (or MKMapRegion, whichever is easier) from these coordinates and then [mapView setVisibleRect:newRect animated:YES] (or [mapView setRegion:newRegion animated:YES] but I'm not quite sure how to get there. I need a method to convert the bounds into the proper data structure, something like:
- (MKMapRect) mapRectThatFitsBoundsSW:(CLLocationCoordinate2D)sw
NE:(CLLocationCoordinate2D)ne {
// CGFloat x = ??
// CGFloat y = ??
// CGFloat width = ??
// CGFloat height = ??
MKMapRect mapRectFromBounds = MKMapRectMake(x,y,width,height);
return mapRectFromBounds;
}
Any thoughts?
There are several ways to do this.
You could create an MKCoordinateRegion by figuring out the center point and then the span is the absolute difference in degrees between the corners.
Or you could create an MKMapRect by using the MapKit function MKMapPointForCoordinate. To get the origin, figure out the northwest coordinate and convert it to an MKMapPoint. To get the width and height, get the absolute difference in mappoints between the corners (convert the corners from coordinates to MKMapPoints using the function first).
Another quick way is a slight trick using the MKMapRectUnion function. Create a zero-size MKMapRect from each coordinate and then merge the two rects into one big rect using the function:
MKMapPoint swPoint = MKMapPointForCoordinate(SWCoordinate);
MKMapRect swRect = MKMapRectMake(swPoint.x, swPoint.y, 0, 0);
MKMapPoint nePoint = MKMapPointForCoordinate(NECoordinate);
MKMapRect neRect = MKMapRectMake(nePoint.x, nePoint.y, 0, 0);
MKMapRect rect = MKMapRectUnion(swRect, neRect);
Remember that the map view will still make its own adjustments to the rect you request based on the proportions of the map view and the required zoom. (If you want to know what that adjusted rect will be, call the map view's mapRectThatFits: method.)
If your bounds can span the 180th meridian, you have to account for that in the conversion:
- (MKMapRect) mapRectThatFitsBoundsSW:(CLLocationCoordinate2D)sw
NE:(CLLocationCoordinate2D)ne
{
MKMapPoint pSW = MKMapPointForCoordinate(sw);
MKMapPoint pNE = MKMapPointForCoordinate(ne);
double antimeridianOveflow =
(ne.longitude > sw.longitude) ? 0 : MKMapSizeWorld.width;
return MKMapRectMake(pSW.x, pNE.y,
(pNE.x - pSW.x) + antimeridianOveflow,
(pSW.y - pNE.y));
}
But beware those MKMapRects that span the anitmeridian, because they come from the land where the dragons live. If you want to learn about some of the dangers that lie there, have a look at
MKMapRect and displaying map overlays that span 180th meridian. You have been warned!
I found something that works. I ended up going with this:
- (MKMapRect) mapRectThatFitsBoundsSW:(CLLocationCoordinate2D)sw
NE:(CLLocationCoordinate2D)ne {
MKMapPoint nePoint = MKMapPointForCoordinate(ne);
MKMapPoint swPoint = MKMapPointForCoordinate(sw);
CGFloat width = ABS(nePoint.x - swPoint.x);
CGFloat height = ABS(nePoint.y - swPoint.y);
MKMapRect newMapRect = MKMapRectMake(
MIN(swPoint.x, nePoint.x),
MIN(swPoint.y, nePoint.y),
width,
height
);
// if (!MKMapRectSpans180thMeridian(newMapRect)) {
return newMapRect;
// } else {
// ????
// }
}

Resources