6

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];
}
Community
  • 1
  • 1
Adam Johnson
  • 673
  • 9
  • 18
  • See the last two lines of code in [this answer](http://stackoverflow.com/questions/29317517/swift-fit-annotations) (don't need the looping or anything -- just the `let edgeInset = ...` onwards). Replace allAnnMapRect with polyline.boundingMapRect. –  Apr 16 '15 at 16:57
  • Anna, that's worked a treat. Thanks for the help. – Adam Johnson Apr 16 '15 at 17:41

3 Answers3

13

This code sets the region to display the entire polyline, along with 12.5% padding on each side:

var regionRect = myPolyline.boundingMapRect

let wPadding = regionRect.size.width * 0.25
let 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)
phi
  • 10,634
  • 6
  • 53
  • 88
user4870792
  • 131
  • 2
2
func zoomToPolyLine(map : MKMapView, polyLine : MKPolyline, animated : Bool)
{
 map.setRegion(MKCoordinateRegionForMapRect(polyLine.boundingMapRect), animated: animated)
 }
RyanTCB
  • 7,400
  • 5
  • 42
  • 62
1

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.

enter image description here

Hope it will help some one.

Arshad Shaik
  • 1,095
  • 12
  • 18