Setting the zoom level for a MKMapView

后端 未结 15 3006
不知归路
不知归路 2020-12-02 05:46

I have a map which shows correctly, the only thing I want to do now is set the zoom level when it loads. Is there a way to do this?

Thanks

15条回答
  •  一向
    一向 (楼主)
    2020-12-02 05:51

    Swift implementation

    import Foundation
    import MapKit
    
    class MapViewWithZoom: MKMapView {
    
        var zoomLevel: Int {
            get {
                return Int(log2(360 * (Double(self.frame.size.width/256) / self.region.span.longitudeDelta)) + 1);
            }
    
            set (newZoomLevel){
                setCenterCoordinate(coordinate:self.centerCoordinate, zoomLevel: newZoomLevel, animated: false)
            }
        }
    
        private func setCenterCoordinate(coordinate: CLLocationCoordinate2D, zoomLevel: Int, animated: Bool) {
            let span = MKCoordinateSpan(latitudeDelta: 0, longitudeDelta: 360 / pow(2, Double(zoomLevel)) * Double(self.frame.size.width) / 256)
            setRegion(MKCoordinateRegion(center: coordinate, span: span), animated: animated)
        }
    }
    

提交回复
热议问题