在Swift中,您应该使用以下代码来定义最小和最大缩放限制
let MIN_ZOOM_LEVEL = 16.5
let MAX_ZOOM_LEVEL = 18.0
extension UIViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
let coordinate = CLLocationCoordinate2DMake(mapView.region.center.latitude, mapView.region.center.longitude)
let zoomLevel = getZoomLevel()
if MIN_ZOOM_LEVEL > zoomLevel || MAX_ZOOM_LEVEL < zoomLevel {
let region = MKCoordinateRegionMake(coordinate, self.latestSpan)
mapView.setRegion(region, animated:true)
} else {
self.latestSpan = MKCoordinateSpanMake(0, 360 / pow(2, Double(zoomLevel-1)) * Double(mapView.frame.size.width) / 256)
}
}
}
func getZoomLevel() -> Double {
var angleCamera = mapView.camera.heading
if angleCamera > 270 {
angleCamera = 360 - angleCamera
} else if angleCamera > 90 {
angleCamera = fabs(angleCamera - 180)
}
let angleRad = M_PI * angleCamera / 180
let width = Double(mapView.frame.size.width)
let height = Double(mapView.frame.size.height)
let heightOffset : Double = 20
let spanStraight = width * mapView.region.span.longitudeDelta / (width * cos(angleRad) + (height - heightOffset) * sin(angleRad))
return log2(360 * ((width / 256) / spanStraight)) + 1
}