I've been looking for a solution to zooming a MapView in to fit the boundaries of an MKPolyline in Swift. I have been able to locate example code for Objective-C here on SO, but I'm not at all familiar with Objective-C or how to convert it into Swift.
Would anyone have an example of this in Swift? Thanks.
-(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];
}
This code sets the region to display the entire polyline, along with 12.5% padding on each side.
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)
If you don't want the padding just do this
var regionRect = myPolyline.boundingMapRect
myMapView.setRegion(MKCoordinateRegionForMapRect(regionRect), animated: true)
func zoomToPolyLine(map : MKMapView, polyLine : MKPolyline, animated : Bool)
{
map.setRegion(MKCoordinateRegionForMapRect(polyLine.boundingMapRect), animated: animated)
}
Write this below lines of code after calculating the directions. The below code works for me.
//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)
The screen shot as below.
Hope it will help some one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With