anon
anon

Reputation:

How to zoom in or out a MKMapView in Swift?

Objective

I need my app to zoom in or out a MKMapView.

Code

I thought of animating the value of the altitude of a MKMapCamera. Though, this doesn't zoom in or out the map.

let mapCamera = MKMapCamera()
    mapCamera.altitude = 1000000
    mapView.camera = mapCamera

    UIView.animateWithDuration(10, delay: 0., options: UIViewAnimationOptions.CurveLinear, animations: {
        mapCamera.altitude = 6000000
        }, completion: {(finished: Bool) in
    })

    mapView.camera = mapCamera

Question

How do I zoom in or out a MKMapView? Are there any other ways to do so?

Upvotes: 0

Views: 9356

Answers (2)

user1488696
user1488696

Reputation:

Here is an extension based on kevins answer https://stackoverflow.com/a/20129379/1488696

With it you'll be able to zoom in and out as required

extension MKMapView {

    // delta is the zoom factor
    // 2 will zoom out x2
    // .5 will zoom in by x2

    func setZoomByDelta(delta: Double, animated: Bool) {
        var _region = region;
        var _span = region.span;
        _span.latitudeDelta *= delta;
        _span.longitudeDelta *= delta;
        _region.span = _span;

        setRegion(_region, animated: animated)
    }
}

Use it like so: myMapView.setZoomByDelta(0.5, animated: true)

MKMapCamera is used for 3D maps. So its likely not what you're looking for

Apple Docs

An MKMapCamera object describes a virtual camera that you use to define the appearance of the map. A camera object creates a virtual viewpoint above the map surface and affects how the map renders its tiles and other content. You use a camera object to specify the location of the camera on the map, the compass heading that corresponds to the camera’s viewing direction, the pitch of the camera relative to the map perpendicular, and the camera’s altitude above the map. These factors let you create a map view that is not just flat but offers a more 3D-like experience."

Upvotes: 3

Duncan C
Duncan C

Reputation: 131481

Use the method setRegion:animated:. It takes an MKCoordinateRegion parameter. The region includes a span, which determines the range of north-to-south latitude shown on the screen.

Upvotes: 0

Related Questions