Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zoom MKMapView to fit polyline points

I have an array, allCollections, that holds programmatically-created arrays of CLLocations the user has recorded through my iOS app. Each sub-array in allCollections holds all the location points in a trip taken.

I draw MKPolylines off of the CLLocations in the arrays in allCollections to represent those trips on an MKMapView. My question is this: With the polylines added to the map, how would I go about programmatically zooming and centering the map to display all of them?

like image 635
user768339 Avatar asked Nov 26 '12 16:11

user768339


2 Answers

-(void)zoomToPolyLine: (MKMapView*)map polyline: (MKPolyline*)polyline animated: (BOOL)animated
{
    [map setVisibleMapRect:[polyline boundingMapRect] edgePadding:UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0) animated:animated];
}
like image 53
fundtimer Avatar answered Oct 22 '22 18:10

fundtimer


in swift:

if let first = mapView.overlays.first {
    let rect = mapView.overlays.reduce(first.boundingMapRect, combine: {MKMapRectUnion($0, $1.boundingMapRect)})
    mapView.setVisibleMapRect(rect, edgePadding: UIEdgeInsets(top: 50.0, left: 50.0, bottom: 50.0, right: 50.0), animated: true)
}

this will zoom/pan to fit all overlays with a little buffer

like image 15
garafajon Avatar answered Oct 22 '22 17:10

garafajon