缩放MKMapView以适合折线点

use*_*339 29 iphone objective-c mkmapview cllocation ios

我有一个数组allCollections,它包含用户通过我的iOS应用程序记录的以编程方式创建的CLLocations数组.allCollections中的每个子数组都包含所有行程中的所有位置点.

我从allCollections中的数组中的CLLocations中绘制MKPolylines来表示MKMapView上的那些行程.我的问题是:将折线添加到地图中,我将如何以编程方式缩放和居中地图以显示所有这些?

小智 67

-(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];
}
Run Code Online (Sandbox Code Playgroud)

  • 对代码的一点解释很好. (2认同)
  • 这适合我.但显然这会将缩放系数设置为**填充**屏幕,而不是**适合**.你能想到一个解决方案吗? (2认同)

Tom*_*Tom 14

-(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];
}
Run Code Online (Sandbox Code Playgroud)

  • 由于MKPolyline已经实现了boundingMapRect,因此不需要创建MKPolygon (2认同)

gar*_*jon 9

在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)
}
Run Code Online (Sandbox Code Playgroud)

这将缩放/平移以适应所有叠加与一点缓冲


Cra*_*aig 8

您可以遍历所有CLLocations记录max/min坐标并使用它来设置视图rect就像在这个问题上一样iOS MKMapView缩放以显示所有标记.

或者您可以浏览每个叠加层boundingMapRect然后使用它们MKMapRectUnion(http://developer.apple.com/library/ios/documentation/MapKit/Reference/MapKitFunctionsReference/Reference/reference.html#//apple_ref/c/func/MKMapRectUnion)将它们全部组合起来,直到你有一个MKMapRect覆盖它们并用它来设置视图.

[mapView setVisibleMapRect:zoomRect animated:YES]
Run Code Online (Sandbox Code Playgroud)

这个问题显示了一个简单的循环,结合了我所建议的联合中的maprects:MKMapRect缩放太多了


Bur*_*000 7

Swift 3版本的garafajon优秀代码

    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)
    }
Run Code Online (Sandbox Code Playgroud)


Jes*_*ess 7

Swift 4 /略微修改版本的基金会的答案.

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

使用路线的折线调用上面的内容并保留默认的非动画,并添加10的小边缘插图:

setVisibleMapArea(polyline: route.polyline, edgeInsets: UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0))
Run Code Online (Sandbox Code Playgroud)