我一直在寻找一种解决方案来缩放MapView以适应Swift中MKPolyline的边界。我已经能够找到Objective-C here on SO的示例代码,但我完全不熟悉Objective-C或者如何将它转换为Swift。
有没有人在Swift中有这样的例子?感谢。
-(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];
}
答案 0 :(得分:6)
此代码将区域设置为显示整条折线,每边都有12.5%的填充。
var regionRect = myPolyline.boundingMapRect
var wPadding = regionRect.size.width * 0.25
var hPadding = regionRect.size.height * 0.25
//Add padding to the region
regionRect.size.width += wPadding
regionRect.size.height += hPadding
//Center the region on the line
regionRect.origin.x -= wPadding / 2
regionRect.origin.y -= hPadding / 2
myMapView.setRegion(MKCoordinateRegionForMapRect(regionRect), animated: true)
如果您不想填充,只需执行此操作
var regionRect = myPolyline.boundingMapRect
myMapView.setRegion(MKCoordinateRegionForMapRect(regionRect), animated: true)
答案 1 :(得分:2)
func zoomToPolyLine(map : MKMapView, polyLine : MKPolyline, animated : Bool)
{
map.setRegion(MKCoordinateRegionForMapRect(polyLine.boundingMapRect), animated: animated)
}
答案 2 :(得分:0)
在计算出方向后,将其写在下面的代码行中。以下代码对我有用。
//this code is used to fit two points polyline in mapview
let newDistance = CLLocation(latitude: pickupCoordinate.latitude, longitude: pickupCoordinate.longitude).distance(from: CLLocation(latitude: destinationCoordinate.latitude, longitude: destinationCoordinate.longitude))
let region = MKCoordinateRegion(center: pickupCoordinate, latitudinalMeters: 2 * newDistance, longitudinalMeters: 2 * newDistance)
let adjustRegion = self.mapView.regionThatFits(region)
self.mapView.setRegion(adjustRegion, animated:true)
屏幕截图如下。
希望这会有所帮助。