views:

44

answers:

2

I'm looking for some help with finishing some code on setting the region on a MKMapView based on the current location annotation and an annotation I have set.

I want to calculate the distance between the two and set the center between the two and then zoom out so both are in view. It appears to work fine in Simulator for me, but unfortunately the userLocation.coordinate is fixed to Apple HQ. When I test on a device, I am seeing weird behaviour. Often it'll zoom out and set a proper region if the two annotations are somewhat horizontally on the same latitude, but if the vertical distance is greater it's not zooming out properly.

I have used code found here, and edited a little bit to fit my needs:

CLLocationCoordinate2D southWest = mapView.userLocation.coordinate;
CLLocationCoordinate2D northEast = southWest;

southWest.latitude = MIN(southWest.latitude, annotation.coordinate.latitude);
southWest.longitude = MIN(southWest.longitude, annotation.coordinate.longitude);

northEast.latitude = MAX(northEast.latitude, annotation.coordinate.latitude);
northEast.longitude = MAX(northEast.longitude, annotation.coordinate.longitude);

CLLocation *locSouthWest = [[CLLocation alloc] initWithLatitude:southWest.latitude longitude:southWest.longitude];
CLLocation *locNorthEast = [[CLLocation alloc] initWithLatitude:northEast.latitude longitude:northEast.longitude];

// This is a diag distance (if you wanted tighter you could do NE-NW or NE-SE)
CLLocationDistance meters = [locSouthWest distanceFromLocation:locNorthEast];

MKCoordinateRegion region;
region.center.latitude = (southWest.latitude + northEast.latitude) / 2.0;
region.center.longitude = (southWest.longitude + northEast.longitude) / 2.0;
region.span.latitudeDelta = meters / 111319.5;
region.span.longitudeDelta = 0.0;

MKCoordinateRegion savedRegion = [mapView regionThatFits:region];
[mapView setRegion:savedRegion animated:YES];

[locSouthWest release];
[locNorthEast release];

One thing that confused me is that he says northEast = southWest...

Thanks in advance to anyone who's got some help and input :)

A: 

this blog posting might provide you with the insight to need

http://codisllc.com/blog/zoom-mkmapview-to-fit-annotations/

Aaron Saunders
Perfect! The deltas were the issue I can see. Thanks so much!
Canada Dev
A: 

Don't get scared by the two first lines, you can ignore what's right of = signs, as it will be overwritten below...

I think the issue is here :

region.span.longitudeDelta = 0.0;
jv42
Yeah, Aaron's link above has the deltas correctly calculated and it appears to have solved it. Just requires a bit of tweaking of the extra margin, but the code's perfect!
Canada Dev