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:
Before we can use the map view there are a few things that we have to do:
- Import MapKit
- Make our controller implement MKMapViewDelegate
- 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) }
Pingback: Swift 2 examples – #4 Add user annotations to a MapView | Juan Carlos Sanchez's Blog
Pingback: Swift 2 examples – #5 Getting the User’s Location | Juan Carlos Sanchez's Blog