Note that there are some explanatory texts on larger screens.

plurals
  1. POSet MKMapView region to center on two annotations
    text
    copied!<p>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.</p> <p>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.</p> <p>I have used code found <a href="https://stackoverflow.com/questions/1336370/positioning-mkmapview-to-show-multiple-annotations-at-once">here</a>, and edited a little bit to fit my needs:</p> <pre><code>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]; </code></pre> <p>One thing that confused me is that he says <code>northEast = southWest</code>...</p> <p>Thanks in advance to anyone who's got some help and input :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload