geohei
geohei

Reputation: 802

MKMapView setRegion() doesn't get correct region after set

My intention was to make an extension to zoom in/out an existing MapView.

extension MKMapView {
    func setZoom(factor: Double, animated: Bool) {
        var zoomedRegion = self.region
        var span = self.region.span
        span.latitudeDelta *= factor
        span.longitudeDelta *= factor
        zoomedRegion.span = span
        setRegion(zoomedRegion, animated: true)
    }
}

So I said ...

let region = ...
mapView.setRegion(region, animated: false) // (*1)
mapView.setZoom(factor: 1.5, animated: true)

The map didn't show the correct region (zommed out region way too much).

After lots of reading/experimenting, I found out that while setting the region properties using .setRegion() (*1), mapView didn't return these values if queried after .setRegion() (*2). That was the reason for my extension above not working as expected.

print("before:", region)
mapView.setRegion(region, animated: false)
print("after :", mapView.region) // (*2)

before: MKCoordinateRegion(center: __C.CLLocationCoordinate2D(latitude: 43.64849335837167, longitude: -0.8807327789450028), span: __C.MKCoordinateSpan(latitudeDelta: 12.608932817799975, longitudeDelta: 14.170354357890005)) // displays correct region
after : MKCoordinateRegion(center: __C.CLLocationCoordinate2D(latitude: 45.81435400000001, longitude: 5.133124999999978), span: __C.MKCoordinateSpan(latitudeDelta: 90.0, longitudeDelta: 180.0)) // some region centered on current position is displayed
  1. Question: Why does mapView.region (*2) above not return the previously set region?

During the tests, I found out that mapView.setRegion(region, animated: false) does (apparently?!) the same as mapView.region = region.

  1. Question: Is there technically any difference between both ways to set the region?

There are posts on SO which suggest to put .setRegion() inside a DispatchQueue or to initialize mapView prior .setRegion(). Both didn't change anything to the above ...

Upvotes: 1

Views: 34

Answers (0)

Related Questions