Last active
April 12, 2017 05:54
-
-
Save dreampowder/3dada8752e814ab08ea38051d4748318 to your computer and use it in GitHub Desktop.
Centering Annotations in mkmapview and objective-c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define MAP_PADDING 2.5 | |
#define MINIMUM_VISIBLE_LATITUDE 0.01 | |
- (void)zoomToAnnotations:(NSArray*)annotationArray{ | |
if (annotationArray.count>0) { | |
CGFloat maxLongitude = -180; | |
CGFloat maxLatitude = -90; | |
CGFloat minLongitude = 180; | |
CGFloat minLatitude = 90; | |
for(StationAnnotation* annotation in annotationArray){ | |
CGFloat lat = annotation.coordinate.latitude; | |
CGFloat lon = annotation.coordinate.longitude; | |
NSLog(@"lat: %f, lon: %f",lat,lon); | |
if (maxLatitude<lat) { | |
maxLatitude = lat; | |
} | |
if(lat<minLatitude){ | |
minLatitude = lat; | |
} | |
if(maxLongitude<lon){ | |
maxLongitude = lon; | |
} | |
if (lon<minLongitude) { | |
minLongitude = lon; | |
} | |
} | |
NSLog(@"maxLat: %f minLat: %f maxLon: %f minLon: %f",maxLatitude,minLatitude,maxLongitude,minLongitude); | |
if (maxLatitude>90) { | |
NSLog(@"maxLat %f",maxLatitude); | |
maxLatitude = 90; | |
} | |
if(minLatitude<-90){ | |
NSLog(@"minLat %f",minLatitude); | |
minLatitude = -90; | |
} | |
if(minLongitude<-180){ | |
NSLog(@"minLon %f",maxLongitude); | |
minLongitude = -180; | |
} | |
if(maxLongitude>180){ | |
NSLog(@"minLon %f",minLongitude); | |
maxLongitude = 180; | |
} | |
MKCoordinateRegion region; | |
region.center.latitude = (minLatitude + maxLatitude) / 2; | |
region.center.longitude = (minLongitude + maxLongitude) / 2; | |
region.span.latitudeDelta = (maxLatitude - minLatitude) * MAP_PADDING; | |
region.span.latitudeDelta = (region.span.latitudeDelta < MINIMUM_VISIBLE_LATITUDE) | |
? MINIMUM_VISIBLE_LATITUDE | |
: region.span.latitudeDelta; | |
region.span.longitudeDelta = (maxLongitude - minLongitude) * MAP_PADDING; | |
MKCoordinateRegion scaledRegion = [self.mapView regionThatFits:region]; | |
@try { | |
[self.mapView setRegion:scaledRegion animated:YES]; | |
} @catch (NSException *exception) { | |
NSLog(@"Exception: %@",exception); | |
} @finally { | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment