-->

MKMapView: Zoom to default “country level”

2020-07-22 09:53发布

问题:

when putting a MKMapView into a UIViewController and setting it to Satellite view, the map is zoomed and adjusted to show the whole country the user is current located in: For example the United States as shown below.

When the user is now zooming the map or I'm zooming the map programmatically, it doesn't seem to be able to restore this default zoom level.

Of course I could find out the coordinates of this default zoom in order to zoom back to that setting, but practically I would need to do that for every single country which isn't really worth it.

Does someone know how to solve this problem?

回答1:

To do that, it needs two types of information. The center coordinates for the selected country and the correct value to set for region.span on the map. It likely has access to that data from the Apple Maps database. I am not aware of that being made public to us. But there are other geocoding databases out there on the internet if you search around that might give you those two values.

If you find one that has what you want, then you set it on the map using:

myMKMapView.region.center = // Center coordinates of country
myMKMapView.region.span = // A value large enough to enclose the country.


回答2:

You could just simply save default area on viewDidAppear and then use it when needed :}

class MyController: UIViewController {
    @IBOutlet weak var mapView: MKMapView!
    var defaultRegion: MKCoordinateRegion?

    override func viewDidAppear(animated: Bool) {
        defaultRegion = mapView.region
    }

    func showDefaultMapArea() {
        if let region = defaultRegion {
            mapView.setRegion(region, animated: true)
        }
    }