Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zoom MKMapView to fit polyline points in Swift

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];
}
like image 980
Adam Johnson Avatar asked Apr 16 '15 13:04

Adam Johnson


3 Answers

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)
like image 109
user4870792 Avatar answered Nov 20 '22 07:11

user4870792


func zoomToPolyLine(map : MKMapView, polyLine : MKPolyline, animated : Bool)
{
 map.setRegion(MKCoordinateRegionForMapRect(polyLine.boundingMapRect), animated: animated)
 }
like image 36
RyanTCB Avatar answered Nov 20 '22 07:11

RyanTCB


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.

like image 1
Arshad Shaik Avatar answered Nov 20 '22 05:11

Arshad Shaik