Zoom MKMapView to fit polyline points

2019-01-13 21:08发布

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?

7条回答
虎瘦雄心在
2楼-- · 2019-01-13 21:36

@Fundtimer pointed it right way, Only thing is that Padding needs to be adjusted as per visual needs, that way it will support all the other overlays and following is the generic solution for all overlays.

-(void)zoomIntoExistingMapObjectForAnnot:(CustomMapAnnotation *)annot
{
   id overlay = annot.shape;//I have overlay property in custom annotation class.
   [_mapView setVisibleMapRect:[overlay boundingMapRect] edgePadding:UIEdgeInsetsMake(150.0, 150.0, 150.0, 150.0) animated:YES];
}
查看更多
Fickle 薄情
3楼-- · 2019-01-13 21:45

Swift 3 version of garafajon excellent code

    if let first = self.mapView.overlays.first {
        let rect = self.mapView.overlays.reduce(first.boundingMapRect, {MKMapRectUnion($0, $1.boundingMapRect)})
        self.mapView.setVisibleMapRect(rect, edgePadding: UIEdgeInsets(top: 50.0, left: 50.0, bottom: 50.0, right: 50.0), animated: true)
    }
查看更多
可以哭但决不认输i
4楼-- · 2019-01-13 21:48

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

查看更多
女痞
5楼-- · 2019-01-13 21:50
-(void)zoomToPolyLine: (MKMapView*)map polyLine: (MKPolyline*)polyLine 
animated (BOOL)animated
{
MKPolygon* polygon = 
    [MKPolygon polygonWithPoints:polyLine.points count:polyLine.pointCount];

[map setRegion:MKCoordinateRegionForMapRect([polygon boundingMapRect]) 
     animated:animated];
}
查看更多
啃猪蹄的小仙女
6楼-- · 2019-01-13 21:53
-(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];
}
查看更多
趁早两清
7楼-- · 2019-01-13 21:55

Swift 4 / slightly modified version of fundtimer's answer.

 func setVisibleMapArea(polyline: MKPolyline, edgeInsets: UIEdgeInsets, animated: Bool = false) {
    mapView.setVisibleMapRect(polyline.boundingMapRect, edgePadding: edgeInsets, animated: animated)
}

Calling the above using a route's polyline and leaving the default of not animated, and adding small edge insets of 10 all around:

setVisibleMapArea(polyline: route.polyline, edgeInsets: UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0))
查看更多
登录 后发表回答