MKMapRect zoomRect = MKMapRectNull;
if ([mView.annotations count] == 0) return;
NSInteger count=0;
for (id <MKAnnotation> annotation in mapView.annotations){
if( [annotation isKindOfClass:[MapViewAnnotation class]] && annotation.coordinate.latitude != 0 && annotation.coordinate.longitude != 0 ){
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(zoomRect)) {
zoomRect = pointRect;
}
else {
zoomRect = MKMapRectUnion(zoomRect, pointRect);
}
count++;
}
}
MKCoordinateRegion region = MKCoordinateRegionForMapRect(zoomRect);
[mapView setRegion:region];
If you need to support iOS3, loop through the annotations to find the top left and bottom most right annotation to figure out largest region to display:
CLLocationCoordinate2D topLeftCoord;
topLeftCoord.latitude = -90;
topLeftCoord.longitude = 180;
CLLocationCoordinate2D bottomRightCoord;
bottomRightCoord.latitude = 90;
bottomRightCoord.longitude = -180;
NSInteger i=0;
for(MapViewAnnotation *annotation in mView.annotations) {
if(
([annotation isKindOfClass:[MapViewAnnotation class]] || [annotation isKindOfClass:[MKPointAnnotation class]] == includeKml)
&& (![annotation isKindOfClass:[MKUserLocation class]])
){
topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
i++;
}
}
MKCoordinateRegion region;
region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1;
// Add a little extra space on the sides
region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1;
// Add a little extra space on the sides
region = [mView regionThatFits:region];
[mView setRegion:region animated:YES];
No comments:
Post a Comment