Amissi Amissi - 1 month ago 20
Swift Question

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)

Answer

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

At the top of your ViewController add the following variable: var restrictedRegion: MKCoordinateRegion!

In your viewDidLoad: restrictedRegion = MKCoordinateRegion(center: location, span: span)!

var manuallyChangingMap = false //Stop from updating while animating
func mapView(mapView: MKMapView!, regionDidChangeAnimated animated: Bool) {
    if (!self.manuallyChangingMap) {
        var updateRegion: Bool = false
        var restrictedRegion: MKCoordinateRegion = self.restrictedRegion

        if ((mapView.region.span.latitudeDelta > restrictedRegion.span.latitudeDelta * 4) || (mapView.region.span.longitudeDelta > restrictedRegion.span.longitudeDelta * 4) ) {
            updateRegion = true
        }

        if (fabs(mapView.region.center.latitude - restrictedRegion.center.latitude) > restrictedRegion.span.latitudeDelta) {
            updateRegion = true
        }

        if (fabs(mapView.region.center.longitude - restrictedRegion.center.longitude) > restrictedRegion.span.longitudeDelta) {
            updateRegion = true
        }
        if (updateRegion) {
            self.manuallyChangingMap = true
            mapView.setRegion(restrictedRegion, animated:true)
            self.manuallyChangingMap = false
        }
    }
}

You will need to set a few variables that are specific to your needs, but I hope this puts you on the right track.

Comments