Swift 2 examples – #3 Set the location of a MapView

This post is part of my collection: Swift 2 – For Beginners.

In this example we will see how to set the location of a MKMapView.

The first thing that we should do is to go to the storyboard and add a Map Kit View to our view:
MapKitView

Before we can use the map view there are a few things that we have to do:

  1. Import MapKit
  2. Make our controller implement MKMapViewDelegate
  3. Add an IBOutlet to our MKMapView
import UIKit
// 1) Import MapKit
import MapKit

// 2) This controller will be the delegate of our mapView
class ViewController: UIViewController, MKMapViewDelegate {

    // 3) Outlet to a MapView in our storyboard
    @IBOutlet weak var map: MKMapView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 4) Set location of the map: Fuengirola - Malaga 36.5417° N, 4.6250° W
        MapHelper.setMapLocation(mapView: map, latitude: 36.548628, longitud: -4.6307649)
    }
}

Now we can implement a method that we can reuse to set the location of our maps. The method setMapLocation will have 4 parameters:

  • mapView, map that will show our location
  • latitud of our location
  • longitud of our location
  • zoom level, by default if not specified will be 1
    static func setMapLocation(mapView mapView: MKMapView, latitude: CLLocationDegrees, longitud: CLLocationDegrees, zoom: Double = 1){
        
        // define the map zoom span
        let latitudZoomLevel : CLLocationDegrees = zoom
        let longitudZoomLevel : CLLocationDegrees = zoom
        let zoomSpan:MKCoordinateSpan = MKCoordinateSpanMake(latitudZoomLevel, longitudZoomLevel)
        
        // use latitud and longitud to create a location coordinate
        let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitud)
        
        // define and set the region of our map using the zoom map and location
        let region:MKCoordinateRegion = MKCoordinateRegionMake(location, zoomSpan)
        mapView.setRegion(region, animated: true)
        
    }

2 thoughts on “Swift 2 examples – #3 Set the location of a MapView

  1. Pingback: Swift 2 examples – #4 Add user annotations to a MapView | Juan Carlos Sanchez's Blog

  2. Pingback: Swift 2 examples – #5 Getting the User’s Location | Juan Carlos Sanchez's Blog

Your feedback is important...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.