import Foundation
import MapKit

extension MKMapView {
    func centerOnPins() {
        var minLat = 0.0, maxLat = 0.0, minLon = 0.0, maxLon = 0.0
        for annotation in self.annotations {
            if annotation.coordinate.latitude < minLat || minLat == 0 { minLat = annotation.coordinate.latitude }
            if annotation.coordinate.latitude > maxLat || maxLat == 0 { maxLat = annotation.coordinate.latitude }
            if annotation.coordinate.longitude < minLon || minLon == 0 { minLon = annotation.coordinate.longitude }
            if annotation.coordinate.longitude > maxLon || maxLon == 0 { maxLon = annotation.coordinate.longitude }
        }
        
        let center = CLLocationCoordinate2D(latitude: (minLat + maxLat)/2, longitude: (minLon + maxLon)/2)
        let leftTop = CLLocation(latitude: minLat, longitude: minLon)
        let rightBottom = CLLocation(latitude: maxLat, longitude: maxLon)
        var diagonal = leftTop.distance(from: rightBottom)*1.2
        if diagonal < 1000 {
            diagonal = 1000
        }
        
        let region = MKCoordinateRegion(center: center, latitudinalMeters: diagonal, longitudinalMeters: diagonal)
        self.setRegion(region, animated: true)
    }
}
