Search code examples
swiftmapkitxcode7-beta2

Swift- MKMapkit view only one city?


I'm trying to make an app viewing the college I'm going to but I'm having trouble only viewing the one city. I'm trying to make sure that the user cannot scroll past the city. I'm then trying to overlay that region. I thought the setRegion method would help fix that issue but apparently not. Any suggestions on how to set the region in which the user cannot surpass?

    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    // sets maps to univeristy
    var location = CLLocationCoordinate2DMake(42.9633,
        -85.890042)
    // Span and region
    var span = MKCoordinateSpanMake (0.005, 0.005)
    var region = MKCoordinateRegion(center: location, span: span)
    Map.setRegion(region, animated: true)

Solution

  • I translated the Obj-C code found here: https://gist.github.com/Alp-Phone/e11cca67e77285566d4d to Swift Link is dead.

    lazy var restrictedRegion: MKCoordinateRegion = {
        // sets maps to univeristy
        let location = CLLocationCoordinate2DMake(42.9633, -85.890042)
        // Span and region
        let span = MKCoordinateSpanMake (0.005, 0.005)
        return MKCoordinateRegion(center: location, span: span)
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.setRegion(restrictedRegion, animated: true)
    }
    
    var manuallyChangingMap = false //Stop from updating while animating
    func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
        if !manuallyChangingMap && ((mapView.region.span.latitudeDelta > restrictedRegion.span.latitudeDelta * 4) ||
                (mapView.region.span.longitudeDelta > restrictedRegion.span.longitudeDelta * 4) ||
                fabs(mapView.region.center.latitude - restrictedRegion.center.latitude) > restrictedRegion.span.latitudeDelta ||
                fabs(mapView.region.center.longitude - restrictedRegion.center.longitude) > restrictedRegion.span.longitudeDelta) {
    
            manuallyChangingMap = true
            mapView.setRegion(restrictedRegion, animated: true)
            manuallyChangingMap = false
        }
    }